【问题标题】:Get exit status of process piped in to another, when using Python paramiko使用 Python paramiko 时,获取通过管道传输到另一个进程的退出状态
【发布时间】:2018-08-18 15:16:29
【问题描述】:

我正在使用 paramiko 向远程主机发送 SSH 命令,并检查生成的错误代码。像这样的:

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, port=port, username=user)
chan = client.get_transport().open_session()
chan.settimeout(timeout)
chan.set_combine_stderr(True)
chan.get_pty()
chan.exec_command(command)
status = int(chan.recv_exit_status())
if status:
    # got a non-0 exit status if I'm in here
    sys.exit(status)
client.close()

这很好用,因为我能够发送 SSH 命令并返回进程的错误代码。但是如果我发送一个涉及管道的 SSH 命令,例如 'echo "hello" |发球台mylog.log'?在这种情况下,上面代码中作为“状态”变量返回的退出状态将是 tee 的退出状态,而不是通过管道传递给它的进程。 (显然这个 echo 命令不会失败,但实际上我要运行一个 shell 脚本并通过管道输入到 tee,这是我很好奇的 shell 脚本的退出状态)。

现在我可以在 bash 脚本中使用 ${PIPESTATUS[0]}。帕拉米科有这样的吗?一种使用 paramiko 的方法,并且能够通过管道进入 tee,并找出管道命令的退出状态?

【问题讨论】:

  • 我没有忘记您的回答,感谢您抽出宝贵时间发布它。我只需要暂时转移项目。我明天会检查这个,并会适当地跟进。谢谢!

标签: python bash shell paramiko exit-code


【解决方案1】:

您可以在通过 paramiko 运行的 bash 脚本中使用 set -eo pipefail。在这种情况下 ;将发送适当的退出状态。

如果运行单个命令,也可以在命令前面加上 set -eo pipefail;{command} 前缀

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-11
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多