1

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)    

2 Answers 2

2

The top is a fancy command that requires a terminal/PTY. 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. The terminal is for interactive human use only. If you want to automate things, do not mess with terminal.

Rather, execute the top in batch mode:

top -b -n 1

See get top output for non interactive shell.

Sign up to request clarification or add additional context in comments.

Comments

0

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)  

1 Comment

That's what I wrote in my answer and I never got any feedback from you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.