另外一种能用的ssh多线程样本
接上篇文章,补锅。之前用另外一种多线程写法逻辑错了,导致实现不了,现在发现了错的地方,补上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# coding=utf-8 import paramiko import threading import time from Queue import Queue ips = ['192.168.122.105','192.168.122.106','192.168.122.101','192.168.122.102','10.1.1.1','192.168.122.23'] def job1(queue): t1 = '/root/.ssh/id_rsa' key_file = paramiko.RSAKey.from_private_key_file(t1) ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) while True: ip = queue.get() print('[{0}] {1}').format(time.asctime(),threading.current_thread()) try: ssh.connect(ip,username='root',pkey=key_file,timeout=3) stdin,stdout,stderr = ssh.exec_command('ip route show') print(stdout.read()) except Exception as e: print(e) finally: ssh.close() queue.task_done() if __name__ == '__main__': queue = Queue() num_threads = len(ips) threads = [] for ip in ips: queue.put(ip) for i in range(num_threads): t1 = threading.Thread(target=job1,args=(queue,)) t1.setDaemon(True) t1.start() queue.join() print('{0:-^40}').format('All done') |