Pyhton 利用threading远程下发文件和远程执行linux系统命令

时间:2021-06-09 16:17:59
 #!/usr/bin/env python
# encoding: utf-8
#__author__ = 'cp'
#__date__ = '21/07/16 上午 10:32'
import threading
import time
import pexpect
import paramiko def copy_file(ip,username,pwd,source_file_name,dest_dir,
flag,result,*args,**kwargs):
#下发文件到目的主机 command='/usr/bin/scp %s %s@%s:%s'%(source_file_name,username,ip,dest_dir)
#print command
#print pwd
#print flag
try:
ssh = pexpect.spawn("%s"%(command),timeout=20)
i=ssh.expect(['password','continue connecting (yes/no)?'])
if i == 0:
ssh.sendline(pwd)
elif i == 1:
ssh.sendline('yes')
ssh.expect('password')
ssh.sendline(pwd)
res = ssh.readlines()
ssh.close()
print '执行结果:%s'%(ip)
print '--------------------------'
for i in res:
print i
result[ip]=flag except pexpect.TIMEOUT:
flag=False
result[ip]=flag
print '执行命令超时'
except Exception,e:
flag=False
result[ip]=flag
print 'error: %s'%(e) def remote_exec_command(ip,username,pwd,command,
result,flag,port=22,*args,**kwargs):
# 远程执行系统命令
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, pwd)
stdin, stdout, stderr = ssh.exec_command(command)
# stdin.write('Y')
res = stdout.readlines()
ssh.close() print '%s:'%(ip)
print '----------------------'
for i in res:
print i
result[ip] = flag
except Exception, e:
flag = False
result[ip]=flag
print e class myThread(threading.Thread):
def __init__(self,name,username,password,action,flag,result,
source_file_name=None,dest_dir=None,cmd=None,
*args,**kwargs):
threading.Thread.__init__(self)
self.result=result
self.name= name
self.username=username
self.password=password
self.action=action
self.flag=flag
self.cmd=cmd
self.source_file_name=source_file_name
self.dest_dir=dest_dir def run(self):
if self.action == 1:
copy_file(ip=self.name,username=self.username,pwd=self.password,
source_file_name=self.source_file_name,
dest_dir=self.dest_dir,
flag=self.flag,
result=self.result) elif self.action == 0:
remote_exec_command(ip=self.name,username=self.username,pwd=self.password,
command=self.cmd,
flag=self.flag,
result=self.result) if __name__ == '__main__':
result={} #目的主机执行结果flag存储
username='admin' #系统用户名
password='test123123' #系统密码
source_file_name='/tmp/toc/test.tar.gz' #要下发的文件名(必须为绝对路径+文件名)
dest_dir='/tmp' #下发到目的主机上的文件存放路径
action=0 #控制整个程序是下发文件还是执行命令
# 0:代表远程执行命令
# 1:代表下发文件
flag=True #标记是否执行成功,如果执行失败flag=False cmd='echo $PATH && free -m' #要远程执行的命令 ips=['192.168.100.175','192.168.100.172'] #要管理的主机IP的列表
for ip in ips:
thread_ip = myThread(name=ip,username=username,password=password,
action=action,cmd=cmd,flag=flag,result=result,
source_file_name=source_file_name,dest_dir=dest_dir)
thread_ip.start() count = threading.activeCount() #当前系统的线程数
num = count -1
if action == 1:
while True:
if len(result) == num:
#print result
print '-'*30
for k,v in result.items():
if v:
print '文件远程下发成功:%s'%(k)
else:
print '文件远程下发失败:%s'%(k)
break
else:
time.sleep(0.5)
continue
elif action == 0:
while True:
if len(result) == num:
#print result
print '-'*30
for k,v in result.items():
if v:
print '命令\'%s\'执行成功:%s'%(cmd,k)
else:
print '命令%s执失败:%s' % (cmd, k)
break
else:
time.sleep(0.5)
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