zoukankan      html  css  js  c++  java
  • 批量远程执行linux服务器程序--基于paramiko(多线程版)

    批量远程执行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 "33[1;31m ...... 请等待......33[0m" open_ip = open(options.server) f = open('Allsystem.log','a') paramiko.util.log_to_file('paramiko.log') up='uptime' df = "df -Ph |awk 'NR == 1 || NR == 6{print $0}'" net="ifconfig |awk 'NR==8'|sed 's/^s*//g'" command = [] command=options.cmd.split(',') print command #command.append(options.cmd) for line in open_ip.readlines(): #for line in subprocess.Popen('cat ip.txt',shell=True).communicate()[0]: ip,user,passwd,port=line.strip().split() cmm=['ping','-c','1','-w','1'] cmm.extend(ip.split()) #print cmm a=subprocess.Popen(cmm,stdout=subprocess.PIPE) a.wait() b=a.returncode if b==0: print "%s is up" % ip port=int(port) aa = threading.Thread(target=ssh2,args=(ip,port,passwd,user,command)) aa.start() aa.join() else:print "%s id down" % ip open_ip.close() f.write('='*20 +'All done' +'='*20 + ' ') f.flush() f.close()

     运行结果如下:

  • 相关阅读:
    视差滚动(Parallax Scrolling)插件补充
    10个最佳的触控手式的JavaScript框架(转)
    50个必备的实用jQuery代码段(转)
    PhoneGap开发不可或缺的五件装备
    优化移动网站的9大窍门(转)
    WSADATA
    htons
    INADDR_ANY
    SOCKADDR_IN
    mysql_query()与mysql_real_query()
  • 原文地址:https://www.cnblogs.com/landhu/p/4961539.html
Copyright © 2011-2022 走看看