【问题标题】:paramiko on windows - does it use cygwin or cmd?Windows 上的 paramiko - 它使用 cygwin 还是 cmd?
【发布时间】:2015-08-13 19:02:47
【问题描述】:

我知道要让 paramiko 的 ssh 连接正常工作,我需要在 Windows 上安装 cygwin。目标是从 Linux 远程运行命令到 Windows 服务器,然后在 Linux 服务器或 Windows 本身上再次处理输出。

我很困惑,因为使用 "ssh_obj.exec_command("ipconfig")" 从 Linux 发送到 Windows 的 "ipconfig" 有效,但 "ssh_obj.exec_command("dir")" 无效 - 尝试给出类似 "cd C: \Users\Administrator" 用于 cmd 或 "cd C:",后跟 Cygwin 中的 "cd Users/Administrator"。它们都不起作用。

那么当我使用 Windows 远程发送命令时 paramiko 使用什么?有人知道吗?

【问题讨论】:

  • paramiko 发送MSG_CHANNEL_REQUEST 以获得"exec"。它的执行方式取决于服务器。可能 Cygwin 的 sshd 守护进程派生了一个新进程并执行 /bin/sh -c command。它不会使用 cmd.exe。 ipconfig 成功是因为它不是 cmd shell 内部命令,而是 ipconfig.exe。如果您想与 shell 交互,请改为调用 invoke_shell。这会发送一个"shell" 请求。
  • 但是invoke_shell也和exec_command一样在打开通道后只返回一个对象。我希望将“dir”的输出提供给我
  • 调用 shell 后,您可以send 命令和recv 输出。 dir 不能在 POSIX shell 中工作;使用send('ls\n')。我想你可以运行cmd,但我不知道你为什么要这样做。
  • 我不确定您希望我如何尝试。你能给我一个两行代码的例子——利用我在第一篇文章顶部的内容吗?谢谢~
  • ssh = paramiko.SSHClient(); ssh.connect(hostname, username, password);chan = ssh.invoke_shell();chan.send('ls\n');while not chan.recv_ready(): pass;output = chan.recv(10000).

标签: windows command cygwin command-line-interface paramiko


【解决方案1】:

用你的话说,Cygwin

根据@eryksun:

Paramiko 发送MSG_CHANNEL_REQUEST 以获取"exec"。它的执行方式取决于服务器。可能 Cygwin 的 sshd 守护进程派生了一个新进程并执行 /bin/sh -c command。它不会使用 cmd.exe。 ipconfig 成功是因为它不是 cmd shell 内部命令,而是 [一个应用程序,] ipconfig.exe。如果您想与 shell 交互,请改为调用 invoke_shell。这会发送一个“shell”请求。

至于为什么两个 exec_command() 调用不能连续正常工作,@eryksun 也提到了这一点。 exec_command() 关闭它正在使用的通道。如果您想拨打多个电话,则需要重新创建频道或客户端。我通常只做频道。这是我为此类交互推荐的代码:

def run_cmd(sshClient, command):
    channel = sshClient.get_transport().open_session()
    channel.get_pty()
    channel.exec_command(command)
    out = channel.makefile().read()
    err = channel.makefile_stderr().read()
    returncode = channel.recv_exit_status()
    channel.close()                       # channel is closed, but not the client
    return out, err, returncode

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username = user, password = pw)
out, err, rc = run_cmd(client, "ifconfig")
# Do whatever with the output
out, err, rc = run_cmd(client, "ls")
# Do whatever with the output

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 2017-04-14
    • 2019-04-04
    • 2010-10-21
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多