Question

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
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top