Paramiko中,exec_command和invoke_shell()的send有什么区别?

10
SSHClient.exec_command() 和使用 SSHClient.invoke_shell 的 send 有什么区别?
我可以使用 exec_command 向 MikroTik 路由器设备发送和执行命令,但无法使用 sendinvoke_shell())执行它。
另一方面,我可以向 Cisco 设备发送和执行命令 sendinvoke_shell()),但无法使用 exec_command 执行它。
我所说的命令是配置命令,例如路由(ip route xxx xxx)、创建 VLAN 或添加 IP 地址等。
1个回答

16

两者的区别在于invoke_shell使用SSH shell通道,而exec_command使用SSH exec通道。

对于用户/开发人员来说,这真正意味着什么取决于SSH服务器,而不是Paramiko本身。


在常见的*nix OpenSSH服务器中:
  • The shell channel executes a login shell (as if you login with SSH terminal client). The shell will then present a command prompt and wait for client/user to type the commands. The purpose of the shell channel is to implement an interactive shell session. So basically it's legitimate use is an implementation of an SSH terminal client. That is something one will do very very rarely. If you do, you typically want to use terminal emulation (Paramiko invoke_shell does that unconditionally, but actually it's possible to open the shell channel without the terminal emulation).

    The shell channel is obviously used by SSH terminal clients (like OpenSSH ssh or PuTTY), under normal circumstances.

    The shell channel is a black box with an input and output. The input and output have no structure. If you for example execute a command by sending it to the input, you will never be able to tell when it ended. If you send two commands to input queue, you won't be able to distinguish what output comes from what command.

  • The exec command takes a command as an "argument" and executes it in an isolated environment – still via user's default shell, but not as a "login" shell, what may cause significant differences in the command execution.

    For a typical example of such difference, see Some Unix commands fail with "<command> not found", when executed using Python Paramiko exec_command.

    The purpose of the exec channel is automating a command execution. So typically you do not want to use a terminal emulation, to avoid the command to do fancy stuff like pagination, coloring and mainly interactive confirmations. That's why the default value of get_pty is False.

    The exec channel is used by OpenSSH ssh or PuTTY plink, when you specify a command to execute on its command line:

    ssh user@host command
    

对于不太常见的SSH服务器,差异甚至可能更大。有些服务器甚至可能不支持其中一种通道。很常见的情况是它们看似都支持,但其中一种(通常是exec)完全无法正常工作。

请参阅使用Paramiko exec_command在设备上执行命令无法正常工作


对于Java/JSch有一个类似的问题:
JSch中'shell'通道和'exec'通道之间的区别是什么?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接