批量远程执行linux服务器程序--基于pxpect(多进程、记日志版)

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

#!/usr/bin/python

'''

Created on 2015-06-09

@author: Administrator

'''

importpexpectimportos,sysfromoptparseimportOptionParserimportlogging,multiprocessingimportlogging.handlers#menueusage='%PRog [-h][-s Servers][-c CMDS][--version]'parser=OptionParser(usage=usage,version='Hu 2.0_20150609')

parser.add_option('-s','--Server',dest='server',default='ip.txt',help='The Server Info')

parser.add_option('-c','--CMDS',dest='cmd',default='pwd',help='You wann to execute commands')

(options,args)=parser.parse_args()printoptions.server,options.cmd

logger=logging.getLogger()

logger.setLevel(logging.DEBUG)

ch=logging.StreamHandler()

cc=logging.handlers.RotatingFileHandler('log.txt', maxBytes = 1024*1024, backupCount = 5)

formatter=logging.Formatter("%(asctime)s-%(name)s-%(levelname)s %(message)s")

ch.setFormatter(formatter)

cc.setFormatter(formatter)

logger.addHandler(ch)

logger.addHandler(cc)#ssh functionsdefconnect(ip,username,passWord,port,prompt=']#'):try:

ssh_newkey='Are you sure you want to continue connecting'child=pexpect.spawn('ssh'+username +'@'+ip+'-p'+port,maxread=5000)

child.logfile=fout

i=child.expect([prompt,'assword:*',ssh_newkey,'refused',pexpect.TIMEOUT,'key.*? failed'])printi#if not False:#print child.before,child.afterifi==0:passelifi==1:printpassword

child.sendline(password)elifi==2:

child.sendline('yes')elifi==4:raiseException('Error TIMEOUT!')elifi==3:print'Connect refused'elifi==5:printchild.before,child.after

os.remove(os.path.expanduser('~')+'/.ssh/known_hosts')

child.expect('#')printchild.after,child.before

child.sendline(options.cmd)

child.expect('#')printchild.before,child.afterprint'The command %s result is:'%options.cmdprintchild.beforeexceptException,e:

logger.error("Connect Error")#check -s isn't exitsifos.path.exists(options.server):

filename=options.serverpasselse:print'Please check %s and ip.txt is exits'%options.server

exit(-1)#executefout=file('mylog.txt','w')forlineinopen(filename):

ip,user,passwd,port=line.strip().split()print'*'*50print'The follow ip is %s:'%ip

p=multiprocessing.Pool(processes=4)

result=p.apply_async(connect,[ip,user,passwd,port])printresult.get()#connect(ip,user,passwd,port)

E-mail:362299908@QQ.com

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航