Search code examples
pythonsshparamiko

Truncated result when using Paramiko invoke_shell


I am using Paramiko invoke_shell to pull results of the top command from a remote system. But I am getting truncated lines when looking at the results.

Code as follows :

channel = token.invoke_shell()

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

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

return (result)

The result is as follows (note cn_node+ is not the complete name, it is longer):

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  28639 root      20   0   17.0g  38912  28336 S 111.1   0.1   1101:49 cn-node+
  29889 root      20   0 3379668  16532  13428 S  94.4   0.1 991:39.71 Flare

If directly ssh'ed into the system and running the command, the result is :

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  28639 root      20   0   17.0g  38912  28336 S 116.7   0.1   1186:17 cn-node-cnfp
  29889 root      20   0 3379668  16796  13428 S  94.4   0.1   1067:53 Flare

Wondering how to get the whole line and not the truncated line (get cn-node-cnfp instead of cn-node+).

Thanks!


Solution

  • Set width parameter of SSHClient.invoke_shell to more than the default value of 80:

    channel = token.invoke_shell(width=160)
    

    Though better is probably to use COLUMN environment variable.

    See Linux: How to not limit output from top based on screen width


    In any case, you in general should not use SSHClient.invoke_shell for automating command execution. Use `SSHClient.exec_command. See What is the difference between exec_command and send with invoke_shell() on Paramiko?