1. 程式人生 > >多程序與多執行緒

多程序與多執行緒

用多執行緒類的繼承的方法來實現金鑰連線的批量操作

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):
# ssh [email protected] # 建立一個ssh物件; client = paramiko.SSHClient() # 返回一個私鑰物件 private_key = paramiko.RSAKey.from_private_key_file('id_rsa') # 2. 解決問題:如果之前沒有;連線過的ip, 會出現 # Are you sure you want to continue connecting (yes/no)? yes
# 自動選擇yes client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 3. 連線伺服器 client.connect(hostname=self.hostname, port=self.port, username=self.user, pkey=private_key ) # 4. 執行操作
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: # 5. 獲取命令的執行結果; result = stdout.read().decode('utf-8') print(result) finally: # 6. 關閉連線 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() #join方法,等待所有的子執行緒結束後執行結束 [thread.join() for thread in threads] print('任務執行結束,執行時間為%s'%(time.time()-start_time)) if __name__ == '__main__': main()

這裡寫圖片描述