运行远程python脚本时具有连续标准输出的Paramiko

时间:2018-11-14 22:48:10

标签: python ssh

我正在尝试使用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上缓冲区的连续/循环命令一起使用。我的问题是,由于某种原因,stdout仅在Python脚本完成运行时才被填充,而Python输出的所有内容仅在脚本完成后才会出现。我希望它在脚本运行时 打印。这是我正在使用的测试脚本:

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

有没有解决的办法,或者我做错了什么?预先感谢。

1 个答案:

答案 0 :(得分:0)

问题解决了。该解决方案实际上非常简单。运行Python脚本(command = 'python3.6 test.py'时,我必须从服务器请求伪终端。在Paramiko中,只需将get_pty bool标志设置为True即可完成此操作。参见下文(请注意get_pty中的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脚本的输出。

相关问题