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 ?
Asked
Active
Viewed 291 times
0
-
It's not the double redirection that's a problem. `ssh` just passes output straight through, so the extra redirection doesn't add any new problem. But [`os.system`](http://docs.python.org/2/library/os.html#os.system) never returns the output, it just passes it through to `stdout`, so with or without the extra redirection, your code doesn't work. – abarnert Jul 08 '13 at 18:17
-
3Also, if you'd read the documentation on [`os.system`](http://docs.python.org/2/library/os.html#os.system), it explicitly tells you that "The [`subprocess`](http://docs.python.org/2/library/subprocess.html) module 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. – abarnert Jul 08 '13 at 18:19
1 Answers
3
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.

Ashwini Chaudhary
- 244,495
- 58
- 464
- 504
-
1+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 … – abarnert Jul 08 '13 at 18:20