您需要将调用放在单独的线程(或进程中,但这可能会过大),这反过来又要求代码位于函数中(无论如何,这是一个好主意:模块的顶部没有大量代码水平)。
例如:
import sys, os, string, threadingimport paramikocmd = "grep -h 'king' /opt/data/horror_20100810*"outlock = threading.Lock()def workon(host): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username='xy', password='xy') stdin, stdout, stderr = ssh.exec_command(cmd) stdin.write('xyn') stdin.flush() with outlock: print stdout.readlines()def main(): hosts = ['10.10.3.10', '10.10.4.12', '10.10.2.15', ] # etc threads = [] for h in hosts: t = threading.Thread(target=workon, args=(h,)) t.start() threads.append(t) for t in threads: t.join()main()If you had many more than five hosts, I would recommend using instead a
“thread pool” architecture and a queue of work units. But, for just five, it’s
simpler to stick to the “dedicated thread” model (especially since there is no
thread pool in the standard library, so you’d need a third party package like
threadpool… or a lot of
subtle custom pre of your own of course;-).



