Paramiko-在“后台"运行命令 [英] Paramiko - Running commands in "background"

查看:394
本文介绍了Paramiko-在“后台"运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用exec_command成功实现了Paramiko,但是,我在远程计算机上运行的命令有时可能需要几分钟才能完成.

I've successfully implemented Paramiko using exec_command, however, the command I'm running on the remote machine(s) can sometimes take several minutes to complete.

在这段时间内,我的Python脚本必须等待远程命令完成并接收标准输出.

During this time my Python script has to wait for the remote command to complete and receive stdout.

我的目标是让远程计算机在后台运行",并允许本地Python脚本通过exec_command发送命令后继续运行.

My goal is to let the remote machine "run in the background", and allow the local Python script to continue once it sends the command via exec_command.

我现在不关心stdout,我只是想绕过等待stdout返回,以便脚本可以在命令在远程计算机上运行时继续运行.

I'm not concerned with stdout at this point, I'm just interested in bypassing waiting for stdout to return so the script can continue on while the command runs on the remote machine.

有什么建议吗?

当前脚本:

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

谢谢!

推荐答案

使用单独的线程运行命令.通常应使用join命令清除线程(希望在程序退出之前运行的daemon线程除外).确切的操作方式取决于程序正在运行的其他内容.但是一个例子是:

Use a separate thread to run the command. Usually threads should be cleaned up with the join command (the exception are daemon threads that you expect to run until your program exits). Exactly how you do that depends on the other stuff your program is running. But an example is:

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

您可以通过将Queue传递给ssh_exec_command并将其放在队列中以供程序稍后处理.

You can make this fancier by passing a Queue to ssh_exec_command and put the result on the queue for processing by your program later.

这篇关于Paramiko-在“后台"运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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