2015-04-01 156 views
1

我已經使用exec_command成功實現了Paramiko,但是,我在遠程計算機上運行的命令有時可能需要幾分鐘才能完成。Paramiko - 在後臺運行命令

在此期間,我的Python腳本必須等待遠程命令完成並接收stdout。

我的目標是讓遠程機器「在後臺運行」,並允許本地Python腳本在通過exec_command發送命令後繼續。

我不關心標準輸出在這一點上,我只是想繞過等待標準輸出返回,以便腳本可以繼續,而命令運行在遠程機器上。

有什麼建議嗎?

當前腳本:

def function(): 
    ssh_object = paramiko.SSHClient() 
    ssh_object.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    ssh_object.connect(address, port=22, username='un', password='pw') 
    command = 'command to run' 

try: 
    stdin, stdout, stderr = ssh_object.exec_command(command) 
    stdout.readlines() 
except: 
    do something else 

謝謝!

回答

1

使用單獨的線程來運行該命令。通常應該使用join命令來清理線程(除非程序退出,否則您希望運行的線程爲daemon)。你的具體做法取決於程序運行的其他內容。但是,一個例子是:

import threading 

def ssh_exec_thread(ssh_object, command): 
    stdin, stdout, stderr = ssh_object.exec_command(command) 
    stdout.readlines() 

def function(): 
    ssh_object = paramiko.SSHClient() 
    ssh_object.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    ssh_object.connect(address, port=22, username='un', password='pw') 
    command = 'command to run' 

    thread = threading.Thread(target=ssh_exec_thread, args=(ssh_object, command) 
    thread.start() 
    ...do something else... 
    thread.join() 

你可以通過一個Queuessh_exec_command使這個票友,後來由你的程序把結果隊列進行處理。

+0

謝謝,我現在就試試這個實現。 – user3582642 2015-04-01 17:22:16

相關問題