2

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 = '[email protected]'

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 [email protected] screen', '-list']' returned non-zero exit status 1
1
  • Have you tried capturing some more output say from stderr of the child process(es)? This may give you a clue as to what's going on... Commented Dec 10, 2013 at 15:41

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I was about to update my question that appending ; exit 0 to my command gets me the desired output. Any drawback to that method?
@RicardoSaporta, If you don't care about the exit code, I think it's okay. BTW, it will not work in Windows cmd.
0

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.

2 Comments

while what you say is accurate, it really provides no useful information
Sorry about that. Was writing while on the go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.