2014-01-06 74 views
0

我在Python中使用Paramiko模塊ssh進入另一臺機器並執行命令。與paramiko運行命令一段時間

該命令調用一個連續產生輸出的程序。我的目標將是這樣運行的東西:

stdin, stdout, stderr = ssh.exec_command(mycommand) 

與附加約束X秒後,「我的命令」被終止,就像按下按Ctrl + C和輸出返回到標準輸出。

有沒有一種方法(或另一種方法)來做到這一點?

回答

1

如果遠程主機運行的是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 

然後優雅地停下來。

相關問題