2016-09-09 41 views
0

我试图在Python脚本中远程执行未知数量的主机上的命令(可能是从一台主机到数百台)。这样做的简单方法如下,但很明显,它可以得到很多主机可笑耗时:Python - 如何远程执行并行进程并检索它们的输出

listOfOutputs = [] 
for host in listOfHosts: 
    output = subprocess.Popen(shlex.split("ssh %s '<command>'" % host), stdout = subprocess.PIPE).communicate()[0] 
    listOfOutputs.append(output) 

有没有办法做同样的事情,但是有命令并行远程执行因此不需要很长时间?

回答

0

您必须在单独的线程中运行Popen.subprocess调用,以便您可以启动尽可能多的程序而不会阻塞主程序。

我做了一个小例子,创建与主机一样多的线程。没有什么大不了,因为线程将主要等待主机回复(否则,线程池会更好)

在我的示例中,我有3个主机,并且我在每个主机上执行ping。输出存储在输出的线程安全列表中,并在最后打印:

import threading 
import subprocess 

listOfOutputs=[] 

lock = threading.Lock() 

def run_command(args): 
    p = subprocess.Popen(["ping","-n","1",args],stdout = subprocess.PIPE) 
    output,err = p.communicate() 
    lock.acquire() # listOfOutputs is thread-safe now 
    listOfOutputs.append(args+": "+output) 
    lock.release() 

threads=[] 
listOfHosts = ['host1','host2','host3'] 
for host in listOfHosts: 
    t = threading.Thread(target=run_command,args=[host]) 
    t.start()   # start in background 
    threads.append(t) # store thread object for future join operation 


[t.join() for t in threads] # wait for all threads to finish 

# print results 
for o in listOfOutputs: 
    print(o) 
    print("-"*50) 
相关问题