能用的样本多线程ssh
众所周知,Py下的多线程一般分为两种写法:继承Threading模块去重写子类,使用run方法;另外就是直接threading.Thread()去实例化一个对象。不知道为何,用后者总是实现不了ssh的多线程批量分发命令。最终用第一种写法实现了,希望有第二种写法的小伙伴分享下。。。(QAQ,可怜可怜Py新手),下面是样本代码:
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 41 |
# coding:utf8 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'] class sshThread(threading.Thread): def __init__(self,queue): threading.Thread.__init__(self) self.queue = queue self.setDaemon(True) self.start() def run(self): sshKey = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa') ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) while True: ip = self.queue.get() print('[{0}] {1} starting').format(time.asctime(),threading.current_thread()) try: ssh.connect(hostname=ip,username='root',pkey=sshKey,timeout=3) stdin,stdout,stderr = ssh.exec_command('ip route show') print(stdout.read()) ssh.close() except Exception as e: print(e) self.queue.task_done() if __name__ == '__main__': num_threads = len(__ips__) queue = Queue() for ip in __ips__: queue.put(ip) for i in range(num_threads): sshThread(queue) queue.join() print('{0:-^40}').format('All done') |