首页 > 解决方案 > 运行远程 python 脚本时具有连续标准输出的 Paramiko

问题描述

我正在尝试使用 Paramiko 运行远程 Python 脚本,并让它将 Python 打印的任何内容实时转发回客户端(即连续标准输出)。我通过以下方式调用我的类来连接到我的服务器:

class SSH:
    client = None

    def __init__(self, address, username, password):
        self.client = client.SSHClient()
        self.client.set_missing_host_key_policy(client.AutoAddPolicy())
        self.client.connect(address, username=username, password=password, look_for_keys=False)

然后我通过我的send_command函数向服务器发送命令:

def send_command(self, command):
    if(self.client):
        stdin, stdout, stderr = self.client.exec_command(command)
        for i in range(5): # just print 5 bytes
            print(stdout.channel.recv(1))
            time.sleep(0.1)
    else:
        print("Connection not opened.")

通常,这适用于任何在循环时填充标准输出缓冲区的连续/循环命令。我的问题是,由于某种原因,stdout 仅在 Python 脚本完成运行时才被填充,而 Python 输出的任何内容只有在脚本完成后才会出现。我希望它在脚本运行时打印。这是我正在使用的测试脚本:

from time import sleep
print("Test.")
sleep(1)
print("Test again.")
sleep(2)
print("Final test.")

有没有办法解决这个问题或者我做错了什么?提前致谢。

标签: pythonssh

解决方案


问题解决了。解决方案实际上非常简单。command运行 Python 脚本 ( = 'python3.6 test.py')时,我必须从服务器请求一个伪终端。这在 Paramiko 中只需将get_ptybool 标志设置为True. 见下文(注意get_ptyin exec_command):

class SSH:
    client = None

    def __init__(self, address, username, password):
        self.client = client.SSHClient()
        self.client.set_missing_host_key_policy(client.AutoAddPolicy())
        self.client.connect(address, username=username, password=password, look_for_keys=False)

    def send_command(self, command):
        if(self.client):
            stdin, stdout, stderr = self.client.exec_command(command, get_pty=True)
            while not stdout.channel.exit_status_ready():
                OUT = stdout.channel.recv(1024)
                print(OUT)
        else:
            print("Connection not opened.")

我现在成功地实时连续打印 Python 脚本的输出。


推荐阅读