【问题标题】:Python - How to remotely execute processes in parallel and retrieve their outputPython - 如何远程并行执行进程并检索其输出
【发布时间】:2023-03-10 06:10:02
【问题描述】:

我正在尝试在 Python 脚本中对未知数量的主机(可能是从一台主机到数百台主机)远程执行命令。执行此操作的简单方法如下,但显然对于许多主机来说它会变得非常耗时:

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

有没有办法做同样的事情,但让命令远程并行执行,这样就不会花很长时间?

【问题讨论】:

    标签: python ssh subprocess popen


    【解决方案1】:

    您必须在单独的线程中运行每个 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)
    

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2014-06-29
      • 2010-10-31
      • 2018-11-19
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多