Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过子流程通过SSH发出命令时正确获取返回代码_Python_Shell_Ssh_Subprocess - Fatal编程技术网

Python 通过子流程通过SSH发出命令时正确获取返回代码

Python 通过子流程通过SSH发出命令时正确获取返回代码,python,shell,ssh,subprocess,Python,Shell,Ssh,Subprocess,我试图通过ssh发出一个命令,并通过子进程获取其返回代码。我有一些代码如下所示: cmd = 'ssh user@ip_addr "some_command"' res = subprocess.check_output( cmd, shell=True, stdout=subprocess.PIPE) 现在,如果cmd只生成一个退出代码(例如,将cmd设置为“exit 1”,然后执行try/catch以查看它是否以非零退出),则此操作非常有效。但是,以下操作将无限期挂

我试图通过ssh发出一个命令,并通过子进程获取其返回代码。我有一些代码如下所示:

cmd = 'ssh user@ip_addr "some_command"'
res = subprocess.check_output(
    cmd,
    shell=True,
    stdout=subprocess.PIPE)
现在,如果cmd只生成一个退出代码(例如,将cmd设置为“exit 1”,然后执行try/catch以查看它是否以非零退出),则此操作非常有效。但是,以下操作将无限期挂起:

cmd = 'ssh user@ip_addr "ls -la && exit 0;"'
res = subprocess.check_output(
    cmd,
    shell=True,
    stdout=subprocess.PIPE)

我看到了,我也看到了,但我仍然不知道该怎么做。我并不在乎命令是否生成输出;我更关心的是退出代码。如果有人知道这样做的最佳方式是什么,或者我是否不恰当地使用了子流程,我将不胜感激。

删除
stdout=subprocess.PIPE
,它应该可以工作;
check\u output
本身捕获输出,因此使用
stdout=subprocess.PIPE
重定向它会导致问题。如果您根本不关心输出,只需使用
subprocess.check\u call
(同样,不要使用
stdout=subprocess.PIPE
)。

不要使用
std{out,err=管道
除非从管道中读取

要在使用
子流程
模块放弃通过ssh发出的命令输出的同时获取返回代码,请执行以下操作:

from subprocess import call, DEVNULL, STDOUT

returncode = call(['ssh', 'user@ip', 'ls -la && exit 0;'],
                  stdin=DEVNULL, stdout=DEVNULL, stderr=STDOUT)
另见


注意:
shell=True
未使用。

check\u output
似乎没有
stdout
参数。你是说那里有
stderr
吗?我有,很抱歉。然后你需要看到关于不使用
stderr=PIPE
的重要通知,因为它可能挂在你指向的链接上。你有没有运行另一个环境中的第二个命令,
ssh
可能一直在等待您的密码?
stdout=PIPE
与问题中描述的行为不对应。
stdout=PIPE
导致立即
ValueError
,而不是“以下无限期挂起”--OP没有向我们显示实际的代码。如果它是
stderr=PIPE
,那么如果它填充了它的stderr操作系统管道缓冲区,进程可能会挂起(在我的机器上大约65K,例如,
调用(['python3','-c','import sys;print(“a”*10**4,file=sys.stderr')),stderr=PIPE)
不挂起).我不知道
ls-la
如何在stderr上生成~65K错误消息。