简体   繁体   English

如何从 Paramiko 通道完全读取缓冲区?

[英]How to read the buffer from Paramiko channel completely?

I am writing a Python script to SSH into my Raspberry Pi-Hole, and stream log data to a remote client.我正在将 Python 脚本写入 SSH 到我的 Raspberry Pi-Hole,并将 stream 日志数据写入远程客户端。 It reads out fine, but will stop before everything in the buffer arrives.它读起来很好,但会在缓冲区中的所有内容到达之前停止。 I know this because the terminal I have opened right next to it running the same command will show more entries.我知道这一点,因为我在它旁边打开的终端运行相同的命令将显示更多条目。 If I continue to browse, those missing entries will arrive at the top of the stack of new data.如果我继续浏览,那些丢失的条目将到达新数据堆栈的顶部。 Any ways to fix this?有什么方法可以解决这个问题? TIA - First Post:) - TIA - 第一篇文章:) -

import paramiko
from pathlib import Path
import time

def main():
    home = str(Path.home())
    command = 'pihole -t'

    client = paramiko.SSHClient()
    client.load_system_host_keys(home + '/.ssh/known_hosts')
    client.connect(hostname='192.168.1.101', username='pi')
    transport = client.get_transport()
    channel = transport.open_session()
    channel.exec_command(command)
    while True:
        buffer = channel.recv(4096).decode('utf-8')
        print(buffer)
        time.sleep(1)



    stdin.close()
    stdout.close()
    stderr.close()
    client.close()



if __name__ == '__main__':
    main()

SOLVED:: https://stackoverflow.com/a/53330517/18318581已解决:: https://stackoverflow.com/a/53330517/18318581

Some minor modifications, calling the get_pty=True flag to request a psuedo-terminal, and calling the data from stdout.channel instead of just channel.recv.一些小的修改,调用 get_pty=True 标志来请求一个伪终端,并从 stdout.channel 而不是仅仅调用 channel.recv 调用数据。 Fixed code below:固定代码如下:

import paramiko
from pathlib import Path
import time

def main():
    home = str(Path.home())
    command = 'pihole -t'

    client = paramiko.SSHClient()
    client.load_system_host_keys(home + '/.ssh/known_hosts')
    client.connect(hostname='192.168.1.101', username='pi')
    transport = client.get_transport()
    channel = transport.open_session()
    stdout, stdin, stderr = client.exec_command(command, get_pty=True)
    while True:
        # while channel.recv_ready():
            buffer = stdout.channel.recv(4096)
            print(buffer.decode('utf-8'))
            time.sleep(1)



    client.close()



if __name__ == '__main__':
    main()

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

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