繁体   English   中英

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

[英]Paramiko with continuous stdout while running remote python script

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

有没有解决的办法,或者我做错了什么? 提前致谢。

问题解决了。 该解决方案实际上非常简单。 运行Python脚本( command = 'python3.6 test.py' )时,我不得不从服务器请求psuedo-terminal。 这是在get_pty完成的,只需将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脚本的输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM