Reputation: 11
I am using Python( OSX Python 2.7.10) to ssh into a Debian box ( Python 2.7.9), then I run a bash script (./capture). The bash script contains some tcpdump commands. The problem I cant figure out is how to display the live results from the running bash script on the terminal.
#!/usr/bin/env python3
import subprocess, os
output = subprocess.run(["ssh", "[email protected]", "sudo ./capture"])
print(output)
I am able to ssh , and run the script successfully, but I get no output. When I hit CTRL C I get the following trace:
**^CTraceback (most recent call last):
File "/Users/junesjoseph/run.py", line 3, in <module>
output = subprocess.run(["ssh", "[email protected]", "sudo ./capture"])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 405, in run
stdout, stderr = process.communicate(input, timeout=timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 835, in communicate
self.wait()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1457, in wait
(pid, sts) = self._try_wait(0)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1404, in _try_wait
(pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt**
Any help is greatly appreciated. thanks
Upvotes: 1
Views: 1019
Reputation: 189377
The object returned by subprocess.run
is a CompletedProcess
object which has attributes which contain the stdout
and stderr
of the completed process. You don't want to print it directly, but you can use it to fetch the attribute you want to print.
import subprocess # no reason to import os
subssh = subprocess.run(["ssh", "[email protected]", "sudo ./capture"],
# Set up for capturing stdout and stderr
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
# Add commonly useful attributes
check=True, universal_newlines=True)
print(subssh.output)
If you really only want the output to be displayed on standard output, capturing it so you can print it is basically superfluous. Just set it up to display directly, simply by not setting stdout
or stderr
to anything:
subssh = subprocess.run(["ssh", "[email protected]", "sudo ./capture"],
# Don't set up for capturing -- leave stdout and stderr alone
check=True, universal_newlines=True)
Perhaps see also Running Bash commands in Python where I have posted a more detailed answer about common problems with subprocess
.
Upvotes: 2