Pyhton 利用threading远程下发文件和远程执行linux系统命令
1 #!/usr/bin/env python 2 # encoding: utf-8 3 #__author__ = 'cp' 4 #__date__ = '21/07/16 上午 10:32' 5 import threading 6 import time 7 import pexpect 8 import paramiko 9 10 def copy_file(ip,username,pwd,source_file_name,dest_dir, 11 flag,result,*args,**kwargs): 12 #下发文件到目的主机 13 14 command='/usr/bin/scp %s %s@%s:%s'%(source_file_name,username,ip,dest_dir) 15 #print command 16 #print pwd 17 #print flag 18 try: 19 ssh = pexpect.spawn("%s"%(command),timeout=20) 20 i=ssh.expect(['password','continue connecting (yes/no)?']) 21 if i == 0: 22 ssh.sendline(pwd) 23 elif i == 1: 24 ssh.sendline('yes') 25 ssh.expect('password') 26 ssh.sendline(pwd) 27 res = ssh.readlines() 28 ssh.close() 29 print '执行结果:%s'%(ip) 30 print '--------------------------' 31 for i in res: 32 print i 33 result[ip]=flag 34 35 except pexpect.TIMEOUT: 36 flag=False 37 result[ip]=flag 38 print '执行命令超时' 39 except Exception,e: 40 flag=False 41 result[ip]=flag 42 print 'error: %s'%(e) 43 44 45 def remote_exec_command(ip,username,pwd,command, 46 result,flag,port=22,*args,**kwargs): 47 # 远程执行系统命令 48 try: 49 ssh = paramiko.SSHClient() 50 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 51 ssh.connect(ip, port, username, pwd) 52 stdin, stdout, stderr = ssh.exec_command(command) 53 # stdin.write('Y') 54 res = stdout.readlines() 55 ssh.close() 56 57 print '%s:'%(ip) 58 print '----------------------' 59 for i in res: 60 print i 61 result[ip] = flag 62 except Exception, e: 63 flag = False 64 result[ip]=flag 65 print e 66 67 68 class myThread(threading.Thread): 69 def __init__(self,name,username,password,action,flag,result, 70 source_file_name=None,dest_dir=None,cmd=None, 71 *args,**kwargs): 72 threading.Thread.__init__(self) 73 self.result=result 74 self.name= name 75 self.username=username 76 self.password=password 77 self.action=action 78 self.flag=flag 79 self.cmd=cmd 80 self.source_file_name=source_file_name 81 self.dest_dir=dest_dir 82 83 def run(self): 84 if self.action == 1: 85 copy_file(ip=self.name,username=self.username,pwd=self.password, 86 source_file_name=self.source_file_name, 87 dest_dir=self.dest_dir, 88 flag=self.flag, 89 result=self.result) 90 91 elif self.action == 0: 92 remote_exec_command(ip=self.name,username=self.username,pwd=self.password, 93 command=self.cmd, 94 flag=self.flag, 95 result=self.result) 96 97 98 99 if __name__ == '__main__': 100 result={} #目的主机执行结果flag存储 101 username='admin' #系统用户名 102 password='test123123' #系统密码 103 source_file_name='/tmp/toc/test.tar.gz' #要下发的文件名(必须为绝对路径+文件名) 104 dest_dir='/tmp' #下发到目的主机上的文件存放路径 105 action=0 #控制整个程序是下发文件还是执行命令 106 # 0:代表远程执行命令 107 # 1:代表下发文件 108 flag=True #标记是否执行成功,如果执行失败flag=False 109 110 cmd='echo $PATH && free -m' #要远程执行的命令 111 112 ips=['192.168.100.175','192.168.100.172'] #要管理的主机IP的列表 113 for ip in ips: 114 thread_ip = myThread(name=ip,username=username,password=password, 115 action=action,cmd=cmd,flag=flag,result=result, 116 source_file_name=source_file_name,dest_dir=dest_dir) 117 thread_ip.start() 118 119 count = threading.activeCount() #当前系统的线程数 120 num = count -1 121 if action == 1: 122 while True: 123 if len(result) == num: 124 #print result 125 print '-'*30 126 for k,v in result.items(): 127 if v: 128 print '文件远程下发成功:%s'%(k) 129 else: 130 print '文件远程下发失败:%s'%(k) 131 break 132 else: 133 time.sleep(0.5) 134 continue 135 elif action == 0: 136 while True: 137 if len(result) == num: 138 #print result 139 print '-'*30 140 for k,v in result.items(): 141 if v: 142 print '命令\'%s\'执行成功:%s'%(cmd,k) 143 else: 144 print '命令%s执失败:%s' % (cmd, k) 145 break 146 else: 147 time.sleep(0.5) 148 continue
说明:
由action控制程序是下发文件还是执行命令(0:远程执行命令; 1:下发文件到远程主机上)
分别利用了pexpect模块和paramiko模块完成和系统的交互
结果:
当action的值为0时
192.168.100.172:
----------------------
/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin
total used free shared buffers cached
Mem: 7872 6719 1152 0 186 2473
-/+ buffers/cache: 4059 3813
Swap: 16383 450 15933
192.168.100.175:
----------------------
/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin
total used free shared buffers cached
Mem: 7872 7676 196 16 186 3796
-/+ buffers/cache: 3692 4179
Swap: 4031 187 3844
------------------------------
命令'echo $PATH && free -m'执行成功:192.168.100.175
命令'echo $PATH && free -m'执行成功:192.168.100.172
当action的值为1时:
执行结果:192.168.100.172
--------------------------
:
test.tar.gz 100% 10MB 682.7KB/s 00:15
执行结果:192.168.100.175
--------------------------
:
test.tar.gz 100% 10MB 682.7KB/s 00:15
------------------------------
文件远程下发成功:192.168.100.175
文件远程下发成功:192.168.100.172