使用Paramiko读取Top命令的输出

我正在用Python编写脚本来login到ssh,并读取刚执行的命令的输出。 我正在使用paramiko包。 我试图执行命令“顶部”,并获得其输出打印在控制台上。 但是,我无法做到这一点。 请find片段:

import sys import time import select import paramiko host = 'localhost' i = 1 # # Try to connect to the host. # Retry a few times if it fails. # while True: print 'Trying to connect to %s (%i/30)' % (host, i) try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, port=22, username='dummy', password='dummy') print "Connected to %s" % host break except paramiko.AuthenticationException: print "Authentication failed when connecting to %s" % host sys.exit(1) except: print "Could not SSH to %s, waiting for it to start" % host i += 1 time.sleep(2) # If we could not connect within time limit if i == 30: print "Could not connect to %s. Giving up" % host sys.exit(1) # Send the command (non-blocking) stdin, stdout, stderr = ssh.exec_command("uname") # Wait for the command to terminate while not stdout.channel.exit_status_ready(): # Only print data if there is data to read in the channel if stdout.channel.recv_ready(): rl, wl, xl = select.select([stdout.channel], [], [], 0.0) if len(rl) > 0: # Print data from stdout print '-------------------------------' print stdout.channel.recv(1024) print '-------------------------------' # Send the command (non-blocking) stdin, stdout, stderr = ssh.exec_command("top -n 1") # Wait for the command to terminate while not stdout.channel.exit_status_ready(): # Only print data if there is data to read in the channel if stdout.channel.recv_ready(): rl, wl, xl = select.select([stdout.channel], [], [], 0.0) if len(rl) > 0: # Print data from stdout print '-------------------------------' print stdout.channel.recv(1024) print '-------------------------------' # Send the command (non-blocking) stdin, stdout, stderr = ssh.exec_command("uname") # Wait for the command to terminate while not stdout.channel.exit_status_ready(): # Only print data if there is data to read in the channel if stdout.channel.recv_ready(): rl, wl, xl = select.select([stdout.channel], [], [], 0.0) if len(rl) > 0: # Print data from stdout print '-------------------------------' print stdout.channel.recv(1024) print '-------------------------------' # # Disconnect from the host # print "Command done, closing SSH connection" ssh.close() 

输出:尝试连接到本地主机(1/30)

连接到本地主机

Linux的

——————————-

Linux的


完成命令,closuresSSH连接

我不确定,我在哪里做错了。 我能够得到其他的Linux命令的输出。 但是不确定,为什么top命令的输出没有被打印。

top通常使用curses进行显示,而不仅仅是打印。 尝试-b批处理选项以及-n 1 (顶部选项因平台而异,请查看联机帮助页)。 而在将来,请尝试更多地隔离问题 – 如果您要在命令行top通过ssh调用top ,而不使用脚本,则仍然存在问题。

正如Jason S指出的那样

 stdin, stdout, stderr = ssh.exec_command("top -b -n1") print stdout.read() 

工作得很好。