线程处理批量问题
import threading
import time
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
class IPThread(threading.Thread):
def __init__(self,cmd,hostname,port=22,user='root'):
super(IPThread, self).__init__()
self.cmd=cmd
self.hostname=hostname
self.port=port
self.user=user
def conn(self):
client = paramiko.SSHClient()
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=self.hostname,
port=self.port,
username=self.user,
pkey=private_key
)
stdin, stdout, stderr = client.exec_command(self.cmd)
except NoValidConnectionsError as e:
print("连接%s失败"%(self.hostname))
except AuthenticationException as e:
print("%s密码错误"%(self.hostname))
else:
result = stdout.read().decode('utf-8')
print(result)
finally:
client.close()
def main():
start_time = time.time()
threads=[]
for count in range(254):
host='172.25.254.%s' %(count+1)
t=IPThread(cmd='hostname',hostname=host)
threads.append(t)
t.start()
[thread.join() for thread in threads]
print('任务执行结束,执行时间为%s'%(time.time()-start_time))
if __name__ == '__main__':
main()