2013-07-10 33 views
2

我很難在後臺使用paramiko運行進程。我用過:在後臺運行的過程

stdin, stdout, stderr = ssh.exec_command('executefile.py &') 

,發現沒有找到executefile.py的進程在運行。

然後我試着用另一種方式爲包括一個反斜槓:

stdin, stdout, stderr = ssh.exec_command('executefile.py \&') 

此方法處理。有一個實例在機器上運行,但並不奇怪,它沒有在後臺運行。我可以知道它不是在後臺運行,因爲代碼在代碼之後的第二行被卡住了。這是

all_inf = stdout.readlines() 

現在代碼不會被超越以上線,除非腳本的過程中被打死。

我正在學習paramiko,任何幫助表示讚賞。

回答

0

我試過transport班,它真的很棒。這裏是我使用的代碼:

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect(hostname = "host_ip", username = "un"], password = "up") 
channel = ssh.get_transport().open_session() 
pty = channel.get_pty() 
shell = ssh.invoke_shell() 
shell.send("cd /my/directory/; nohup ./exec_name > /dev/null 2>&1 &\n") 

但我仍然不知道如何使用python腳本殺死它;我對此有個疑問here

編輯1:

我已經解決了關於莫名其妙地殺死進程我的問題;你可以檢查它。

3

exec_command未在交互式shell中執行該命令,因此「在後臺運行進程」實際上沒有意義。

如果你真的想要做到這一點,你可以使用命令nohup來啓動你的進程,並在會話退出時保持活動狀態。請記住,當你這樣做時,你不能得到stdin,stdout或stderr,因爲你正在從shell中分離進程,所以相應地重定向它們。

2

你可以試試:

​​3210
+0

與asyncssh相同 – gzerone

2

我試過這裏here描述沒有成功的所有方法,終於意識到,你需要使用的通道,而不是使用SSHClient直接調用exec_command(這背景)不工作:

client = paramiko.SSHClient() 
client.connect(
    ip_address, username='root', pkey=paramiko_key, timeout=5) 
client.exec_command('python script.py > /dev/null 2>&1 &') 

您應該創建和使用一個通道,這部作品在後臺

client = paramiko.SSHClient() 
client.connect(
    ip_address, username='root', pkey=paramiko_key, timeout=5) 
transport = client.get_transport() 
channel = transport.open_session() 
channel.exec_command('python script.py > /dev/null 2>&1 &') 

所以nohup,dtach,screen等實際上沒有必要。

0

你可以嘗試使用屏幕

screen -d -m ping 8.8.8.8 

這將啓動屏幕和ping 8.8.8.8。您可以通過使用

screen -ls 

查看這個畫面,並附上使用

screen -D <<screen_name>> 

注意,命令執行完畢後,屏幕將終止。