Collect output from top command using Paramiko in Python

六眼飞鱼酱① 提交于 2021-02-19 08:50:52

问题


Here I am trying to execute ssh commands and print the output. It works fine except the command top. Any lead how to collect the output from 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)    

回答1:


The top is a fancy command that requires a terminal. While you can enable the terminal emulation using get_pty argument of SSHClient.exec_command, it would get you lot of garbage with ANSI escape codes. I'm not sure you want that.

Rather, execute the top in batch mode:

top -b -n 1

See get top output for non interactive shell.




回答2:


There is an option in exe_command, [get_pty=True] which provides pseudo-terminal. Here I have got an output by adding the same in my code.

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)  


来源:https://stackoverflow.com/questions/65993207/collect-output-from-top-command-using-paramiko-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!