最近做自己開發用相關服務的一個checklist,就寫了這個腳本,用來在跳板機去檢查各個服務器上面的相關服務是否正常
使用expect登錄每個機器(因為安全問題,不能直接使用ssh信任),然后根據yaml文件的配置讀取服務名字以及啟動的進程數量 去檢查每個服務是否正常 PS:難點是沒有用端口轉發也只有普通用戶權限
checklist.py
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]
#我這是使用了-F 是因為我沒有root權限不能修改hosts文件,但是我在config.yaml使用了別名,
而這個定義就是自定義了sshconfig,默認是~/.ssh/config
child = pexpect.spawn('ssh -F /tmp/sshconfig dongwm@{0}'.format(SERVER['host']))
#因為有其他用戶,可能他還沒有鏈接過某服務器,最開始會讓你確認服務器標識,需要點yes
f = child.expect(['Password: ', 'password: ', 'continue connecting (yes/no)?'])
if f == 2:
#當這個flag為2 表示那個用戶沒有登錄過某服務器
child.sendline('yes')
child.expect('password:')
child.sendline('{0}'.format(mypasswd(SERVER['host']))) #mypasswd是加密我服務器權限的函數,每個服務器密碼不同
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 我這里只截取了其中一段
新聞熱點
疑難解答
圖片精選