python paramiko_具有连续标准输出,非一次性读全

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

要完全读取Paramiko通道的缓冲区,可以使用以下代码:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('somecommand')

# Read the buffer from the channel until there is no more data
buffer_data = b''
while not stdout.channel.exit_status_ready():
    buffer_data += stdout.channel.recv(1024)

# 由于在退出时,stdout还是会有一次输出,因此需要单独处理,处理完之后,就可以跳出了
    if stdout.channel.exit_status_ready():
buffer_data += stdout.channel.recv(1024)


# Decode the buffer data
output = buffer_data.decode('utf-8')

# Print the command output
print(output)

ssh.close()

该代码通过使用Paramiko的exec_command函数执行命令并获取执行输出的标准通道(stdout)。使用while循环,将标准通道的缓冲区分段读取并存储在buffer_data中,直到没有更多的数据可读。最后,将缓冲区数据解码为UTF-8格式的文本,并将其打印到控制台上。最后,关闭SSH连接。

这样,就能够完全读取Paramiko通道的缓冲区。

https://www.volcengine.com/theme/5448736-R-7-1

https://cloud.tencent.com/developer/ask/sof/102350820

https://cloud.tencent.com/developer/article/1071078

posted @   卡卡西殿  阅读(165)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示