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



我正在将SSH的Python脚本写入我的Raspberry Pi Hole,并将日志数据流式传输到远程客户端。它的读数很好,但会在缓冲区中的所有内容到达之前停止。我知道这一点,因为我打开的终端旁边运行相同的命令会显示更多的条目。如果我继续浏览,那些丢失的条目将到达新数据堆栈的顶部。有什么办法解决这个问题吗?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()

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

一些小的修改,调用get_pty=True标志来请求psuedo终端,并从stdout.channel而不仅仅是channel.recv调用数据。修复了以下代码:

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()

最新更新