[英]Reading output of Top command using Paramiko
我正在用Python寫一個腳本來登錄ssh並讀取剛剛執行的命令的輸出。 我正在使用paramiko包。 我正在嘗試執行命令“top”並在控制台上打印其輸出。 但是,我無法做到這一點。 請找到代碼段:
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()
輸出:嘗試連接到localhost(1/30)
Linux的
Linux的
命令完成,關閉SSH連接
我不確定,我做錯了什么。 我能夠獲得其他linux命令的輸出。 但不確定,為什么top命令的輸出沒有打印出來。
top
通常使用curses進行顯示而不僅僅是打印。 嘗試使用-b
作為批處理選項以及您擁有的-n 1
(頂部選項因平台而異,請查看聯機幫助頁)。 並且在將來,嘗試更多地隔離問題 - 如果您在命令行top
通過ssh
調用top
而沒有腳本,那么您仍然會遇到問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.