Reputation: 10131
I am using the Paramiko module in Python to ssh into another machine and execute a command.
The command invokes a program that produces output continuously. My goal would be to run something like this:
stdin, stdout, stderr = ssh.exec_command(mycommand)
with the additional constraint that after X seconds "my command" is terminated, just like pressing Ctrl + C and return the output to stdout.
Is there a way (or an alternative way) to do it?
Upvotes: 0
Views: 477
Reputation: 34823
If the remote host is running Unix, you can pass a shell script to do this as mycommand
:
stdin, stdout, stderr = client.exec_command(
"""
# simple command that prints nonstop output; & runs it in background
python -c '
import sys
import time
while 1:
print time.time()
sys.stdout.flush()
time.sleep(0.1)
' &
KILLPID=$!; # save PID of background process
sleep 2; # or however many seconds you'd like to sleep
kill $KILLPID
""")
When run, this prints the current time at 100ms intervals for 2 seconds:
... 1388989588.39
... 1388989588.49
... 1388989588.59
... 1388989588.69
... 1388989588.79
... 1388989588.89
... 1388989588.99
... 1388989589.1
... 1388989589.2
... 1388989589.3
... 1388989589.4
... 1388989589.5
... 1388989589.6
... 1388989589.71
... 1388989589.81
... 1388989589.91
... 1388989590.01
... 1388989590.11
... 1388989590.21
... 1388989590.32
and then gracefully stops.
Upvotes: 1