等待任务通过 Python 在远程机器上完成 [英] Wait until task is completed on Remote Machine through Python

查看:48
本文介绍了等待任务通过 Python 在远程机器上完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Ubuntu 上用 python 编写程序.在该程序中,我试图在连接到网络的远程机器 (RaspberryPi) 上完成删除文件"任务后打印一条消息.

I am writing a program in python on Ubuntu. In that program I am trying to print a message after completing a task "Delete a File" on Remote machine (RaspberryPi), connected to network.

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

But In actual practice, print command is not waiting till completion of task on remote machine.

有人可以指导我如何做吗?我的编码如下

Can anybody guide me on how do I do that? My Coding is given below

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()

推荐答案

这确实是 paramiko SSH exec_command(shell script) 在完成之前返回,但是那里的答案不是很详细.所以...

This is indeed a duplicate of paramiko SSH exec_command(shell script) returns before completion, but the answer there is not terribly detailed. So...

如您所见,exec_command 是一个非阻塞调用.因此,您必须使用以下任一方法等待远程命令完成:

As you noticed, exec_command is a non-blocking call. So you have to wait for completion of the remote command by using either:

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

In your particular case, you need the later:

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()

这篇关于等待任务通过 Python 在远程机器上完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆