【问题标题】:Python execute remote command and don't wait for returnPython执行远程命令并且不等待返回
【发布时间】:2015-01-27 18:03:42
【问题描述】:

我正在测试一个 corosync 集群。我正在尝试使具有浮动 IP 的接口失败,以确保资源使用 python 迁移到另一个节点。

现在的困境是我的命令确实在远程机器上执行,但我的测试代码永远挂起,等待它永远不会得到的回复——由于注入失败,节点将重新启动。

ssh = SSHClient(self.get_ms_ip(ms),
                        self.get_ms_user(ms),
                        self.get_ms_password(ms))
ssh.connect()
self.logger.info("Failing FIP eth now on %s" % ms)
ssh.exec_command(cmd, timeout=1)
#Code never reached this comment.

在python中,我怎样才能发送命令并继续而不等待任何返回?我已经尝试按照这里的建议Run Process and Don't Wait 用 subprocess.Popen 包装我的 ssh.exec_command,但这并没有产生任何不同。

【问题讨论】:

标签: python paramiko remotecommand


【解决方案1】:

你不想要一个子进程,你想要一个线程。生成一个运行 exec_command 调用的线程,您将能够继续编写代码。

【讨论】:

    【解决方案2】:

    你试过nohup吗?

    ssh.exec_command('nohup %s &'%cmd, timeout=1)
    

    【讨论】:

    • 试过 nohup 并且代码确实继续但现在我的 cmd 失败了。以下是我的 cmd: cmd = "echo %s | sudo -S ifdown eth3" % self.get_ms_root_password(ms)
    • 试试这个包装。更容易执行 sudo 命令。 stackoverflow.com/a/22592827/2854735
    【解决方案3】:

    Python 不能很好地处理线程;无法手动退出线程。我最终不得不创建一个工作方法来创建 shh 连接并运行将作为单独的 multiprocessing.Process 运行的 exec_command。

    通过这种方式,我能够在下一次测试运行之前正确地在测试后进行清理(作为 python 单元测试框架的一部分)。

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2011-09-20
      • 2021-07-05
      • 1970-01-01
      相关资源
      最近更新 更多