subprocess ssh命令对于某些命令失败,但对于其他命令则失败(命令在终端中有效) [英] subprocess ssh command fails for some commands but not others (command works in terminal)

查看:84
本文介绍了subprocess ssh命令对于某些命令失败,但对于其他命令则失败(命令在终端中有效)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为python脚本的一部分,我希望捕获通过ssh执行的shell命令的输出,即

As part of a python script, I am hoping to capture the output of a shell command executed via ssh, namely

ssh User@999 screen -list

如果直接在终端中执行上述命令,则会得到所需的结果.但是,当通过如下所示的subprocess.check_output执行时,出现了non-zero exit status 1错误.

If I execute the above command directly in terminal, I get the results I need. However, when executing through subprocess.check_output as below, I get a non-zero exit status 1 error.

我能够通过ssh执行其他命令并捕获输出而不会出现问题.
关于screen -list的某些特定内容,不喜欢以这种方式被调用?

I am able to execute other commands via ssh and capture the output without problem.
Is there something specific about screen -list that does not like being called in this fashion?

import subprocess 

srvr = 'User@999.99.999.9'

print("CMD 1: ===============")
cmd1 = "ssh " + srvr + " ls -l"
print ("COMMAND IS .....  " + cmd1 + "\n")
out1 = subprocess.check_output(cmd1, shell=True)
print(out1 + "\n")

print("CMD 2: ===============")
cmd2 = "ssh " + srvr + " screen -list"
print ("COMMAND IS .....  " + cmd2 + "\n")
out2 = subprocess.check_output(cmd2, shell=True)
print(out2 + "\n")

错误:

subprocess.CalledProcessError: Command '['ssh User@999.99.999.9 screen', '-list']' returned non-zero exit status 1

推荐答案

subprocess.check_output 检查子流程的退出代码;如果退出代码不为零,则会引发异常.

subprocess.check_output check the exit code of the subprocess; and it raises exception if the exit code is not zero.

如果您不关心退出代码,请使用 subprocess.Popen.communicate :

If you don't care about exit code, use subprocess.Popen.communicate:

out1, err1 = subprocess.Popen(cmd1,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE).communicate()

这篇关于subprocess ssh命令对于某些命令失败,但对于其他命令则失败(命令在终端中有效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆