如果遠程主機運行的是Unix,你可以通過一個shell腳本來完成這個作爲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
""")
運行時,該打印在100周毫秒的時間間隔當前時間2秒:
... 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
然後優雅地停下來。