0

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 ?

2
  • 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 never returns the output, it just passes it through to stdout, so with or without the extra redirection, your code doesn't work. Commented Jul 8, 2013 at 18:17
  • 3
    Also, if you'd read the documentation on os.system, it explicitly tells you that "The subprocess 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. Commented Jul 8, 2013 at 18:19

1 Answer 1

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

1 Comment

+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 …

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.