How to get each dependent command execution output using Paramiko exec_command

末鹿安然 提交于 2019-12-06 14:42:27

问题


I'm using Paramiko in order to execute a single or a multiple commands and get its output.

Since Paramiko doesn't allow executing multiple commands on the same channel session I'm concatenating each command from my command list and executing it in a single line, but the output can be a whole large output text depending on the commands so it's difficult to differentiate which output is for each command.

ssh.exec_command("pwd ls- l cd / ls -l")

I want to have something like:

command_output = [('pwd','output_for_pwd'),('ls -l','output_for_ls'), ... ]

to work easier with every command output.

Is there a way to do it without changing the Paramiko library?


回答1:


The only solution is (as @Barmar already suggested) to insert unique separator between individual commands. Like:

pwd && echo "end-of-pwd" && cd /foo && echo "end-of-cd" && ls -l && echo "end-of-ls"

And then look for the unique string in the output.


Though imo, it is much better to simply separate the commands into individual exec_command calls. Though I do not really think that you need to execute multiple commands in a row often. Usually you only need something like, cd or set, and these commands do not really output anything.

Like:

  1. pwd
  2. ls -la /foo (or cd /foo && ls -la)

For a similar question (for "shell" channel), see:
Execute multiple dependent commands individually with Paramiko and find out when each command finishes




回答2:


I used to do this for sending commands in ssh and telnet, you can capture the output with each command and try.

cmd = ['pwd', 'ls - lrt', 'exit']
cmd_output =[]
for cmd in cmd:
    tn.write(cmd)
    tn.write("\r\n")
    out = tn.read_until('#')
    cmd_output.append((cmd,out))
    print out


来源:https://stackoverflow.com/questions/58179070/how-to-get-each-dependent-command-execution-output-using-paramiko-exec-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!