Pythonで複数のサーバーのプロセスを確認するスクリプト

checklist.py

#coding=utf-8
import sys

sys.path.append('/tmp/local/lib/python2.6/site-packages/PyYAML-3.10-py2.6-linux-x86_64.egg’) #依赖yaml
sys.path.append('/tmp/local/lib/python2.6/site-packages/pexpect-2.4-py2.6.egg’) #依赖pexpect
import yaml
import pexpect
dataDict = yaml.load(open('/tmp/config.yaml’)) #yamlをインポート
def myprint(color,mes): #端末カラー印刷関数
"’ANSIカラー端末ディスクプレイ制御コード"’
d = dict(r=31, g=32, gb=36, y=33, b=34, p=35, o=37)
color = “\x1B[%d;%dm" % (1, d[color])
print “%s%s\x1B[0m" % (color, mes)
def main():
list = ['g’, 'b’, 'y’, 'gb’, 'p’]
light = 0
for k in dataDict:
if k.startswith('bj-'):
color = list[light%5]
SERVER = dataDict[k]

child = pexpect.spawn('ssh -F /tmp/sshconfig dongwm@{0}’.format(SERVER['host’]))

f = child.expect(['Password: ', 'password: ', 'continue connecting (yes/no)?’])
if f == 2:

child.sendline('yes’)
child.expect('password:’)
child.sendline('{0}’.format(mypasswd(SERVER['host’])))
if f == 1:
child.sendline('{0}’.format(mypasswd(SERVER['host’])))
child.expect('~’)
for service in SERVER['service’]:
flag = 0
#プロセス数を確認
if isinstance(service, dict):
data =service.items()[0]
service = data[0]
num = data[1]
else:

num = 0
flag = 1
child.expect('~’)
child.sendline('ps -ef|grep {0}|grep -v grep|wc -l’.format(
service))
child.readline()
#プロセス数
pro_num = child.readline().split('\r\n’)[0]
if int(pro_num) == num or flag:

myprint(color, '[{0}] [{1}] [{2}] [{3}]’.format(k.center(12),
SERVER['ip’].center(14), service.center(20), 'ok’.center(4)))
else:
myprint('r’, '[{0}] [{1}] [{2}] [{3}] [{4}!={5}]’.format(k.center(12),
SERVER['ip’].center(14), service.center(20), 'fail’,
pro_num, num))
light += 1
child.sendline('exit’)
if __name__ == '__main__’:
main()

config.yaml

bj-2:
host: s233 #sshconfigでhostを設定
ip: XXX.XXX.XXX.233 #ipの確認
service: #load後ろリスト表
#XX用
– nginx: 5
– uwsgi: 25
– supervisord: 1
#ローカルでmysqlサービスを提供
– mysql: 3 #django
#ローカルでXXを提供
– celery: 12

– rabbitmq: 9
– redis: 1
– mongod: 2

PostgreSQL

Posted by arkgame