1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 import paramiko 4 import threading 5 6 7 class SSHServer: 8 def __init__(self, host_name, host_port, host_username, host_password): 9 transport = paramiko.Transport((host_name, host_port)) 10 transport.connect(username=host_username, password=host_password) 11 self._transport = transport 12 13 def run_cmd(self, command): 14 ssh = paramiko.SSHClient() 15 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 16 ssh._transport = self._transport 17 stdin, stdout, stderr = ssh.exec_command(command) 18 result = stdout.read() 19 print(result.decode()) 20 return result 21 22 def upload(self, local_path, remote_path): 23 sftp = paramiko.SFTPClient.from_transport(self._transport) 24 sftp.put(local_path, remote_path) 25 26 def download(self, remote_path, local_path): 27 sftp = paramiko.SFTPClient.from_transport(self._transport) 28 sftp.get(remote_path, local_path) 29 30 def close(self): 31 self._transport.close() 32 33 def __str__(self): 34 print(self._transport) 35 36 37 if __name__ == '__main__': 38 for line in open('ip.txt', 'r'): 39 cmd_li = line.split() 40 obj = SSHServer(host_name=cmd_li[0], host_port=22, host_username='root', host_password='123456') 41 t = threading.Thread(target=obj.run_cmd, args=('ls; hostname -I',)) 42 t.start() 43 obj.close()
这两天在线上写了一个多线程批量执行的脚本,对300多态服务器执行批量操作。每次执行时,最后一台就会报错!本来以为是本机的python有问题,后来把本机的IP地址,从'ip.txt'中去除,还是会有最后一台服务器执行不成功,报错的内容都一样。请大神指点,看看我是什么原因。我用的python版本为python2.7.5
文件"ip.txt"为ip地址列表
每次报错都一样,报错的内容如下:
打一下所有的line看有没有一行空的。
没有,每一行都有对应的IP地址