批量远程执行linux服务器程序--基于paramiko(多线程版)

时间:2023-03-08 17:08:13
批量远程执行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 + '\n')% ip)
for COMM in comm:
#print COMM
stdin,stdout,stderr = ssh.exec_command(COMM)
print "%s The command %s result is:\n" % (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 "\033[1;31m ...... 请等待......\033[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','','-w','']
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 + '\n')
f.flush()
f.close()

运行结果如下:

批量远程执行linux服务器程序--基于paramiko(多线程版)