• 批量远程执行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()

     运行结果如下:

  • 相关阅读:
    base64URL处理
    智慧幼儿园方案:AI技术如何助力幼儿园智慧建设?
    TSINGSEE青犀视频开发webrtc项目如何实现Windows视频采集?
    国内采用HTTP协议传输视频都有什么优势?
    如何根据直播场景选择合适的直播协议?
    EasyPlayer-RTSP WebActiveX注册提示failed to create control 未指定错误
    luogu题解P2312解方程--暴力模+秦九韶
    【补充习题四】凑微分技巧与积分因子法解常微分方程
    【GMOJ7177】鱼跃龙门
    【洛谷P1791】人员雇佣
  • 原文地址:https://www.cnblogs.com/landhu/p/4961539.html
Copyright © 2020-2023  润新知