最近做自己開發用相關服務的一個checklist,就寫了這個腳本,用來在跳板機去檢查各個服務器上面的相關服務是否正常
使用expect登錄每個機器(因為安全問題,不能直接使用ssh信任),然后根據yaml文件的配置讀取服務名字以及啟動的進程數量 去檢查每個服務是否正常 PS:難點是沒有用端口轉發也只有普通用戶權限
checklist.py
代碼如下:
#coding=utf-8
import sys
#因為我這個腳本要讓很多人能運行,但是不能給他們看見我的密碼算法,所以是pyc
#我這個腳本要給很多其他普通用戶去用,是用我的ssh登錄操作,不能放在我的home目錄,所以放在tmp
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配置load進來
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是加密我服務器權限的函數,每個服務器密碼不同
新聞熱點
疑難解答