【问题标题】:Paramiko with continuous stdout while running remote python script运行远程 python 脚本时具有连续标准输出的 Paramiko
【发布时间】:2018-11-14 22:48:09
【问题描述】:

我正在尝试使用 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.")

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

【问题讨论】:

    标签: python ssh


    【解决方案1】:

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

    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 脚本的输出。

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多