清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
在批量服务器密码统一的情况下使用:
参数介绍:
-u 用户名
-p 密码
-P port
-s 要执行的脚本
-c 要执行的命令
-f 要执行的服务器IP列表
指定-s的时候,直接执行脚本,跳过-c
#!/bin/env python import paramiko import sys,os import time from optparse import OptionParser parser = OptionParser(add_help_option=0) parser.add_option("-f", "--file", action="store", type="string", dest="listfile",default="") parser.add_option("-u", "--user", action="store", type="string", dest="username",default="root") parser.add_option("-p", "--passwd", action="store", type="string", dest="password",default="mypass") parser.add_option("-P", "--port", action="store", type="string", dest="port",default="22") parser.add_option("-c", "--cmd", action="store", type="string", dest="cmdline",default="hostname") parser.add_option("-s", "--script", action="store", type="string", dest="script",default="") (options, args) = parser.parse_args() listfile=options.listfile username = options.username passwd = options.password port = options.port rcmd = options.cmdline scriptfile = options.script time_now = time.strftime('%Y%m%d%H%M%S') infofile="log/info.txt" if os.path.isdir("log"): pass else: os.mkdir("log") if os.path.isfile(infofile): os.rename(infofile,infofile+time_now) info = open(infofile,"a") def execmd(host,port,username,passwd,rcmd): #info = open(infofile,"a") try: client = paramiko.SSHClient() #client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host,port=int(port),username=username,password=passwd,timeout=1) #rcmd = "ifconfig eth0|grep HWaddr|awk '{print $NF}'" print rcmd stdin, stdout, stderr = client.exec_command(rcmd) #info.write(host+"\n"+"@"*20+"\n") for line in stdout: info.write("%s: %s"%(host,line)) client.close() except: info.write("%s: SSH Login Faild\n\n"%(host)) #info.close() def transfile(): try: trans = paramiko.Transport((host,int(port))) trans.connect(username=username,password=passwd) sftp = paramiko.SFTPClient.from_transport(trans) #sftp.get("","") sftp.put(scriptfile,"/tmp/%s"%scriptfile) trans.close() except: #print "File translation faild" info.write("%s: File translation faild\n"%(host)) if __name__=="__main__": for ipaddr in open(listfile).readlines(): host = ipaddr.strip("\n").rstrip().lstrip() print host if scriptfile == "": pass else: transfile() rcmd="sh /tmp/%s"%scriptfile execmd(host,port,username,passwd,rcmd) info.close()本文由 坤子的blog 原创