批量远程执行linux服务器程序--基于paramiko
paramiko模块是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接
具体安装方法这里不写,网上一大把
#!/usr/bin/python #coding:utf-8 import paramiko import threading import os,sys,time import subprocess from optparse import OptionParser import logging usage='%prog [-h][-f file][-c CMDS][--version]' parser=OptionParser(usage=usage,version='HuZhiQiang 2.0_20150618') parser.add_option('-f','--File',dest='server',default='ip.txt',help='The Server Info') parser.add_option('-c','--CMDS',dest='cmd',default="uptime,top -n 1,df -Ph |awk 'NR == 1 || NR == 6{print $0}',ifconfig |awk 'NR==8'|sed 's/^s*//g'",help='You wann to execute commands') (options,args)=parser.parse_args()
#日志记录这里注释了,有需要的可以打开
''' logging.basicConfig(Level=logging.INFO) logger=logging.getLogger(__name__) handler=logging.FileHandler('rem.log') handler.setLevel(logging.INFO) formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) ''' #print options.server,options.cmd def ssh2(ip,pt,pw,us,comm): try: ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #logging.INFO( "%s %s %s" % ('*'*50,ip,'*'*50) ) ssh.connect(ip,port=pt,username=us,password=pw) f.write(('='*20 +'%s status' +'='*20 + ' ')% ip) for COMM in comm: #print COMM stdin,stdout,stderr = ssh.exec_command(COMM) print "%s The command %s result is: " % (time.strftime("%Y%m%d %H:%M:%S"),COMM) read = stdout.read() print read print '-'*60 f.write(read) ssh.close() # except SyntaxError: # print "please checking" # sys.exit() except: print "SSH Connection refused"
print "-" *60
sys.exit() if __name__ == '__main__': if os.path.exists(options.server): filename=options.server pass else: print 'Please check %s and ip.txt is exits' % options.server exit(-1) print "