You probably want to use an SSH library like paramiko
(or spur
, Fabric, etc.… just google/PyPI/SO-search for "Python SSH" to see all the options and pick the one that best matches your use case). There are demos included with paramiko
that do exactly what you want to do.
If you insist on scripting the command-line ssh
tool, you (a) almost certainly want to use subprocess
instead of os.system
(as the os.system
docs explicitly say), and (b) will need to do some bash-scripting (assuming the remote side is running bash) to pass the value back to you (e.g., wrap it in a one-liner script that prints the exit status on stderr
).
If you just want to know why your existing code doesn't work, let's take a look at it:
os.system("ssh -qt hostname 'sudo yum list updates --security > /tmp/yum_update_packagelist.txt';echo $?")
First, you're running an ssh
command, then a separate echo $?
command, which will echo the exit status of ssh
. If you wanted to echo the status of the sudo
, you need to get the semicolon into the ssh
command. (And if you wanted the status of the yum
, inside the sudo
.)
Second, os.system
doesn't look at what gets printed to stdout
anyway. As the docs clearly say, "the return value is the exit status of the process". So, you're getting back the exit status of the echo
command, which is pretty much guaranteed to be 0.'
So, to make this work, you'd need to get the echo into the right place, and then read the stdout by using subprocess.check_output
or similar instead of os.system
, and then parse that output to read the last line. If you do all that, it should work. But again, you shouldn't do all that; just use paramiko
or another SSH library.