I am using a script where I issue a shell command to a remote server (ssh) using os.system() command. I need to collect the output of the command I executed on the remote server. The problem is the double redirection. I am using the os.system() to execute a ssh command which executes the intended command on a remote server. It is this output I intend to make use of. I just need some pointers as to how this can be achieved ?
1 Answer
Use the subprocess module:
subprocess.check_output returns the output of a command as a string.
>>> import subprocess
>>> print subprocess.check_output.__doc__
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
1 Comment
abarnert
+1. And it also has the advantage of letting you pass args as a list instead of having to figure out the mess of double shell-quoting that comes from building an
ssh command line, and making it impossible to forget to check the exit status, and …
sshjust passes output straight through, so the extra redirection doesn't add any new problem. Butos.systemnever returns the output, it just passes it through tostdout, so with or without the extra redirection, your code doesn't work.os.system, it explicitly tells you that "Thesubprocessmodule provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function." And then it links to a section showing how to do exactly what you're asking.