如何从Paramiko通道完整读取缓冲区?
我正在编写一个 Python 脚本,通过 SSH 连接到我的 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()
I am writing a Python script to SSH into my Raspberry Pi-Hole, and stream log data to a remote client. 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 :) -
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已解决!: https://stackoverflow.com/a/53330517/18318581
一些小的修改,调用 get_pty=True 标志请求一个伪终端,并从 stdout.channel 调用数据,而不仅仅是 channel.recv。固定代码如下:
SOLVED!: 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. Fixed code below: