【问题标题】:how to use paramiko ssh object to send remote calls to Windows and Linux server?如何使用 paramiko ssh 对象向 Windows 和 Linux 服务器发送远程调用?
【发布时间】:2015-08-13 16:35:49
【问题描述】:

我正在使用 Python 2.7.6 和 Paramiko 模块(在 Linux 服务器上)连接到 Windows 服务器并发送一些命令并获取输出。我有一个连接函数,它接受远程 Windows 服务器的 IP、用户名和密码,当发生这种情况时我会得到一个 sshobj。我的问题是如何使用它发送远程呼叫?

如果是本地系统,我只会说“os.system”,但不确定远程调用。有人可以帮忙吗?

我的代码如下所示: sys.path.append("/home/me/code")

import libs.ssh_connect as ssh
ssh_obj = ssh.new_conn(IP, username, password)

stdin, stdout, stderr = ssh_obj.exec_command("dir") #since the remote    system I am SSHing into is Windows.

我的“new_conn”看起来像这样:

import paramiko
def new_conn(IP, username, password):
    ssh_obj = paramiko.SSHClient()
    ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_conn.connect(IP, username, password), timeout=30)
    return ssh_obj

我从 stdin、stdout 和 stderror 得到的只是“活动的;1 个打开的频道和一些信息,如 ChannelFile、aes 等..)。

我希望在我的 Linux 上看到来自 Windows 的“dir”输出..

尝试了“stdout.read()”和“stdout.readlines()”,但前者出现了“stdout”,而后者出现了“[]”!

谢谢!

【问题讨论】:

  • JFYI - 我在 Linux 服务器上执行上述代码并将它们发送到 Windows 服务器 .. 因此使用“dir”命令。不过我想在 Linux 服务器上处理它们..
  • 如果我将“dir”替换为“ipconfig”,它可以正常工作。我想知道如何使“dir”工作..

标签: python linux windows paramiko


【解决方案1】:

最新的 Windows 版本具有内置 SSH 客户端/服务器,请参阅 here

【讨论】:

    【解决方案2】:

    我在我的 Windows 上安装了 FreeSSHd,它工作正常!

    FreeSSHd 教程:(中文) https://jingyan.baidu.com/article/f7ff0bfc1ebd322e27bb1344.html

    代码:(Python 3)

    import paramiko
    
    hostname = "windows-hostname"
    username = "windows-username"
    password = "windows-password"
    
    cmd = 'ifconfig'
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname,username=username,password=password)
        print("Connected to %s" % hostname)
    except paramiko.AuthenticationException:
        print("Failed to connect to %s due to wrong username/password" %hostname)
        exit(1)
    except Exception as e:
        print(e.message)    
        exit(2)
    
    try:
        stdin, stdout, stderr = ssh.exec_command(cmd)
    except Exception as e:
        print(e.message)
    
    err = ''.join(stderr.readlines())
    out = ''.join(stdout.readlines())
    final_output = str(out)+str(err)
    print(final_output)
    

    【讨论】:

    • FreeSSHd 如果安全是一个问题,可能不应该使用。它已多年未维护,当前版本 (1.3.1) 存在已知漏洞 (CVE-2018-9853) medium.com/@TheWindowsTwin/…
    【解决方案3】:

    您需要在dir 之前添加cmd.exe /c 作为cmd.exe /c dir 才能在Windows 上远程运行命令。

    坚持执行 exec_command,不要尝试发送/接收命令。我从来没有在 Windows 上使用过 send/recv 命令,至少在我在 windows (FreeSSHd) 上使用的 SSH 服务器上是这样。

    【讨论】:

      猜你喜欢
      • 2011-06-30
      • 2023-02-20
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 2013-07-07
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多