1. 程式人生 > >多執行緒查系統(類的繼承)

多執行緒查系統(類的繼承)

import threading                                                                         
import paramiko                                                                          
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException       
class unameThread(threading.Thread)
:
def __init__(self,cmd,hostname,port=22,user='root'): super(unameThread, self).__init__() self.cmd = cmd self.hostname = hostname self.port = port self.user = user def
run(self):
client = paramiko.SSHClient() private_key = paramiko.RSAKey.from_private_key_file('hhh.py') 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)) except TimeoutError as e: print("%s連線超時" % (self.hostname)) else: result = stdout.read().decode('utf-8') print("%s執行結果:" % (self.hostname), result) finally: client.close() def use_thread(): threads = [] for count in range(254): host = '172.25.254.%s' % (count + 1) t = unameThread("uname",host) threads.append(t) t.start() _ = [thread.join() for thread in threads] print("任務執行結束.....") if __name__=="__main__": use_thread()

這裡寫圖片描述