需求:集群内有100台主机,boss提供了主机列表及信息的excel文档要求:(1)检验密码是否正确 (2)巡检主机健康状况(3)分发文件至主机设计:使用python脚本的paramiko模块登录主机
需求:集群内有100台主机,boss提供了主机列表及信息的excel文档
要求:
(1)检验密码是否正确 (2)巡检主机健康状况(3)分发文件至主机
设计:使用python脚本的paramiko模块登录主机执行命名或分发文件,使用multiprocessing多进程提高执行效率。
具体实现脚本如下:
A.根据boss给的excel生成配置文件信息(支持excel文件和txt文件)
文件格式如下(excel文件会跳过首行,默认首行是描述,且excel中sheet页须注明information):
localhost1 127.0.0.1 22 test testlocalhost2 127.0.0.2 22 test testlocalhost3 127.0.0.3 22 test test
生成conf文件内容信息如下(密码使用了base64简单加密):
[host]connList=['localhost1', 'localhost2', 'localhost3'][information]localhost1={'ip':'127.0.0.1','port':'22','user':'test','password':'dGVzdA=='} localhost2={'ip':'127.0.0.2','port':'22','user':'test','password':'dGVzdA=='} localhost3={'ip':'127.0.0.3','port':'22','user':'test','password':'dGVzdA=='}
生成配置信息代码:
#!/usr/bin/env python#-*- coding:utf-8 -*-#auth:dWX278035#update:2017/2/18 16:19 #description:mkPasswdimport sys,os,xlrd,base64''' 解析文件内容 '''def analyzeFile(fileName): _list = [] _hosts = [] if fileName.split('.')[1] == 'xlsx': ''' Excel文件使用xlrd包解析 ''' print u'开始解析excel文件...' data = xlrd.open_workbook(fileName) table = data.sheet_by_name(u'information') nrows = table.nrows for i in range(nrows - 1): hostname = table.cell(i+1,0).value ip = table.cell(i+1,1).value port = int(table.cell(i+1,2).value) user = table.cell(i+1,3).value password = base64.b64encode(table.cell(i+1,4).value) _hosts.append(hostname) _list.append('''%s={'ip':'%s','port':'%s','user':'%s','password':'%s'} ''' %(hostname,ip,port,user,password)) elif fileName.split('.')[1] == 'txt': ''' Txt文件直接解析,文件分隔符为tab或者space ''' print u'开始解析txt文件...' with open(fileName,'r') as f: for line in f: _info = line.split() hostname = _info[0] ip = _info[1] port = _info[2] user = _info[3] password = base64.b64encode(_info[4]) _hosts.append(hostname) _list.append('''%s={'ip':'%s','port':'%s','user':'%s','password':'%s'} ''' %(hostname,ip,port,user,password)) else: raise Exception(u'只支持.txt和.xlsx文件...') print u'解析文件完成...' return _list,_hosts''' 将解析的内容写入conf文件 '''def writeToFile(str): with open('example.conf','ab+') as f: f.write('%s/n' %(str))''' 写入文件前若文件存在则删除 '''def chkFiles(): print u'检查example.conf文件是否存在....' if os.path.exists('example.conf'): print u'删除example.conf文件...' os.remove('example.conf')if __name__ == '__main__': chkFiles() if len(sys.argv) < 2: print ''' Usage : pyton %s example.xlsx ''' %(sys.argv[0]) sys.exit() else: if not os.path.exists(sys.argv[1]): raise Exception(u'指定文件不存在...') _list,_hosts = analyzeFile(sys.argv[1]) print u'开始写入文件...' writeToFile('[host]') writeToFile('connList=%s' %(str(_hosts).replace('u/'','/''))) writeToFile('/n[information]') for _ in _list: writeToFile(str(_)) print u'写入文件完成[example.conf],程序退出...'