You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Paramiko invoke_shell执行top命令结果行截断的解决咨询

解决Paramiko invoke_shell获取top结果行截断问题

问题原因

通过invoke_shell模拟终端执行top时,默认终端宽度有限,top会自动截断COMMAND列内容以适配终端宽度,导致命令名称显示不完整(比如cn-node-cnfp变成cn-node+)。而直接SSH登录时终端宽度足够,所以能显示完整名称。

解决方案

有两种可靠的解决方式:

方式1:指定top以批处理模式运行并设置输出宽度

使用top的-b(批处理模式,适合脚本执行)和-w(指定输出宽度)参数,让top忽略终端尺寸,输出完整内容。

修改后的代码:

channel = token.invoke_shell()

channel.send('terminal length 0\n')
time.sleep(1)
resp = channel.recv(9999)
output = resp.decode('ascii')

# 使用batch模式并指定宽度200(可根据实际需求调整)
channel.send('top -n 1 -b -w 200\n')
time.sleep(1)
resp = channel.recv(9999)
output = resp.decode('ascii')
result = ''.join(output)

return result

方式2:调整模拟终端的宽度

在执行top前,通过stty cols命令设置终端的列数,让模拟终端拥有足够宽度来显示完整内容。

修改后的代码:

channel = token.invoke_shell()

channel.send('terminal length 0\n')
time.sleep(1)
resp = channel.recv(9999)
output = resp.decode('ascii')

# 设置终端列数为200(可按需调整)
channel.send('stty cols 200\n')
time.sleep(0.5)
resp = channel.recv(9999)

channel.send('top -n 1\n')
time.sleep(1)
resp = channel.recv(9999)
output = resp.decode('ascii')
result = ''.join(output)

return result

说明

  • 批处理模式(-b)是top专为非交互式场景设计的模式,输出格式更稳定,不会受终端尺寸影响,推荐优先使用。
  • 终端宽度值(200)可根据实际最长命令名称调整,确保能容纳完整内容。

内容的提问来源于stack exchange,提问作者Dan G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:30:37