使用Paramiko执行ESXi的esxtop命令无法获取完整输出
解决Paramiko执行ESXi esxtop无法获取完整输出的问题
我明白你碰到的麻烦了——esxtop本身是交互式的实时监控工具,默认会持续刷新输出且不会自动退出,这就是你的脚本没法拿到完整输出,甚至可能一直卡在读取步骤里的原因。下面给你两个针对性的解决方案:
方案1:用非交互式批量模式获取单次完整输出
esxtop支持-b(batch批量模式)和-n(指定输出次数)参数,能让它一次性输出指定次数的监控数据后自动退出,这样Paramiko就能完整读取所有内容。
修改后的完整代码示例:
import paramiko # 1. 建立SSH连接 ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect("your-esxi-host", username="root", password="your-password") # 2. 执行非交互式esxtop命令,-n 1表示只输出1次数据后退出 stdin, stdout, stderr = ssh_client.exec_command("TERM=xterm esxtop -b -n 1", get_pty=True) # 3. 读取并写入输出到文件 with open("output.txt", "w") as outfile: # 命令会自动退出,直接读取所有输出即可 output = stdout.read() outfile.write(output) # 关闭连接 ssh_client.close()
方案2:持续监控一段时间后主动终止esxtop
如果你需要获取一段时间内的持续输出,可以在让esxtop运行指定时长后,发送终止信号(比如Ctrl+C)停止命令,这样就能拿到截止到终止时的所有输出。
示例代码:
import paramiko import time ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect("your-esxi-host", username="root", password="your-password") stdin, stdout, stderr = ssh_client.exec_command("TERM=xterm esxtop", get_pty=True) # 让esxtop运行5秒后终止 time.sleep(5) # 发送Ctrl+C信号终止命令 stdin.write("\x03") stdin.flush() # 读取所有输出并写入文件 with open("output.txt", "w") as outfile: outfile.write(stdout.read()) ssh_client.close()
为什么原来的方法行不通?
原来的esxtop在默认交互式模式下会持续运行并刷新输出,不会主动退出,导致stdout.readline会一直等待新的输出行,脚本无法自动结束,自然也没法拿到"完整"的输出(因为输出是无限持续的)。通过批量模式或主动终止命令,才能让Paramiko完整读取到所有输出内容。
内容的提问来源于stack exchange,提问作者Arshpreet Singh
相关产品推荐
相关产品推荐

