subprocess ssh command fails for some commands but not others (command works in terminal)

孤人 提交于 2019-12-24 01:28:34

问题


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

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.

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")

Error:

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

回答1:


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

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

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



回答2:


That's how subprocess.check_output() is supposed to work. See: http://docs.python.org/2/library/subprocess.html

The command on your server is returning a non zero return code and thus is raising the appropriate Exception CalledProcessError.



来源:https://stackoverflow.com/questions/20498536/subprocess-ssh-command-fails-for-some-commands-but-not-others-command-works-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!