【问题标题】:Paramiko SSH exec_command (shell script) returns before completionParamiko SSH exec_command(shell 脚本)在完成前返回
【发布时间】:2011-03-14 01:03:36
【问题描述】:

我使用 Paramiko 从远程 Linux 机器启动一个 shell 脚本。启动 shell 脚本并执行命令make -j8。但是 exec_command 在 make 完成之前返回。

如果我在本地机器上启动脚本,它会正确执行。

有人可以解释一下这种行为吗?

【问题讨论】:

    标签: python ssh paramiko


    【解决方案1】:

    您需要等待应用程序完成,exec_command 不是阻塞调用。

    print now(), "before call"
    stdin, stdout, sterr = ssh.exec_command("sleep(10)")
    print now(), "after call"
    channel = stdout.channel
    print now(), "before status"
    status = channel.recv_exit_status()
    print now(), "after status"
    

    【讨论】:

    • 奇怪的是,使用 stdout.channel.recv_exit_status() 会永远阻塞我的代码
    • @sliders_alpha 事实上,虽然这个答案原则上是正确的,但如果命令的输出足够大,这个简单的实现将挂起/死锁。见Paramiko ssh die/hang with big output