shell 在Python中使用Paramiko从top命令收集输出

qcbq4gxm  于 2023-06-24  发布在  Shell
关注(0)|答案(2)|浏览(210)

在这里,我尝试执行ssh命令并打印输出。除了top命令外,它工作正常。任何铅如何收集从顶部的输出?

import paramiko
from paramiko import SSHClient, AutoAddPolicy, RSAKey

output_cmd_list = ['ls','top']

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname_ip, port, username, password)

for each_command in output_cmd_list:
    stdin, stdout, stderr = ssh.exec_command(each_command)
    stdout.channel.recv_exit_status()
    outlines = stdout.readlines()
    resp = ''.join(outlines)
    print(resp)
hl0ma9xz

hl0ma9xz1#

top是一个需要终端/PTY的花哨命令。虽然您可以使用SSHClient.exec_commandget_pty参数启用终端仿真,但它会给您带来大量ANSI转义码垃圾。我不确定你想这样。终端仅供交互式人类使用。如果你想让事情自动化,就不要和终端打交道。
相反,以批处理模式执行top

top -b -n 1

参见get top output for non interactive shell

k3fezbri

k3fezbri2#

exe_command中有一个选项[get_pty=True],它提供了伪终端。在这里,我通过在代码中添加相同的内容得到了一个输出。

import paramiko
from paramiko import SSHClient, AutoAddPolicy, RSAKey

output_cmd_list = ['ls','top']

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname_ip, port, username, password)

for command in output_cmd_list:
    stdin, stdout, stderr = ssh.exec_command(command,get_pty=True)
    stdout.channel.recv_exit_status()
    outlines = stdout.readlines()
    resp = ''.join(outlines)
    print(resp)

相关问题