等到通过Python在远程计算机上完成任务

问题描述 投票:8回答:2

我在Ubuntu上用python编写程序。在该程序中,我尝试在连接到网络的远程计算机(RaspberryPi)上完成“删除文件”任务后打印一条消息。

但在实际操作中,打印命令不会等到远程机器上的任务完成。

任何人都可以指导我如何做到这一点?我的编码如下

import paramiko

# Connection with remote machine
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')

filename   = 'fahad.txt'
filedelete ='rm ' + filename
stdin, stdout, stderr = client.exec_command(filedelete)
print ("File Deleted")
client.close()
python python-2.7 remote-access paramiko
2个回答
27
投票

这确实是paramiko SSH exec_command(shell script) returns before completion的副本,但答案并不是非常详细。所以...

正如你所注意到的那样,exec_command是一个非阻塞的电话。因此,您必须使用以下任一方法等待远程命令的完成:

在您的特定情况下,您需要后者:

stdin, stdout, stderr = client.exec_command(filedelete)  # Non-blocking call
exit_status = stdout.channel.recv_exit_status()          # Blocking call
if exit_status == 0:
    print ("File Deleted")
else:
    print("Error", exit_status)
client.close()

3
投票

除了做Sylvian Leroux建议的事情:

如果您的命令涉及运行bash脚本,该脚本需要在paramiko关闭ssh会话后继续运行(每次发送命令时都会发生这种情况)使用:

nohup ./my_bash_script.sh >/dev/null 2>&1

nohup告诉系统该进程应该忽略ssh会话关闭时收到的“挂断”信号。

>/dev/null 2>&1重定向输出。这是必要的,因为在某些情况下,在收到输出之前,控件不会返回到python脚本。

要运行命令行应用程序,如“stress”和“vlc”,并在返回后继续运行,我找到的唯一解决方案是将命令放在bash脚本中,后跟&&>/dev/null,而不是使用paramiko调用bash脚本我在前一段中提到的方法。

这似乎有点“hacky”,但这是我经过几天搜索后找到的唯一方法。

© www.soinside.com 2019 - 2024. All rights reserved.