Paramiko在运行远程python脚本时使用连续标准输出

2024-04-16 06:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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脚本运行完成时才会填充stdout,而Python输出的任何内容都只有在脚本运行完成后才会出现。我希望它在脚本运行时打印。这是我正在使用的测试脚本:

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

是有办法解决这个问题还是我做错了什么?提前谢谢。你知道吗


Tags: 命令self脚本clientsend内容foraddress
1条回答
网友
1楼 · 发布于 2024-04-16 06:31:45

问题解决了。解决办法其实很简单。在运行Python脚本(command='python3.6 test.py')时,我必须从服务器请求psuedo终端。在Paramiko中,只需将get_ptybool标志设置为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脚本的输出。你知道吗

相关问题 更多 >