Python paramiko/sshtunnel 代码在 Linux 下工作正常,但在 Windows 下失败

标签 python linux windows paramiko ssh-tunnel

我已经成功获得了以下 python paramiko/sshtunnel 代码,可以在 Linux 下正常工作,通过 SSH 隧道隧道到远程计算机上的端口。然而,在 Windows 10 下运行完全相同的 python 代码会失败。这两种情况都是 Python 3.9.5。

首先,代码本身...

import sys
import json
import time
import queue
import socket
import paramiko
import sshtunnel
from threading import Thread

remotehost = 'remote-host-blah-blah-blah.net'
remoteport = 9999
pkeyfile   = os.path.expanduser('~/.ssh/id_rsa')

def main():
    pkey = paramiko.RSAKey.from_private_key_file(pkeyfile)
    with sshtunnel.open_tunnel(
        (remotehost, 22),
        ssh_username='remoteusername',
        ssh_pkey=pkey,
        compression=True,
        remote_bind_address=('0.0.0.0', remoteport)
    ) as remote:
        connecthost = remote.local_bind_host
        connectport = remote.local_bind_port
        return runit(connecthost, connectport)
    return 1

def runit(connecthost, connectport):
    client = None

    while True:
        try:
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect((connecthost, connectport))
            output(f'\nconnected: {connecthost}:{connectport}')
            break
        except Exception as e:
            time.sleep(1.0)
            print(f'!!! retrying {connecthost}:{connectport} because of {e}')

    # If we made it here, we are properly connected through
    # the tunnel. This works under linux, but we never get
    # here under Windows 10. The code which follows is not
    # pertinent to this Stackoverflow question, so I have
    # left out the remaining code in this program.

这是不断打印的错误...

!!! retrying 0.0.0.0:53906 because of [WinError 10049] The requested address is not valid in its context

当然,每次运行时“53906”端口都是不同的。

此外,在 Windows 10 下,我可以在这个 python 程序运行时转到 Power Shell,并且可以运行以下命令,在这种情况下,我确实连接到端口并查看远程数据...

telnet localhost 53906

这似乎意味着 python 尝试连接到该套接字的方式导致了错误。

任何人都可以看到我可能需要在 python 代码中更改哪些内容才能使其在 Windows 10 下正常工作吗?

非常感谢。

最佳答案

我发现了问题并解决了它。

这两行返回 connecthost = '0.0.0.0' 和 connectport 的随机值:

        connecthost = remote.local_bind_host
        connectport = remote.local_bind_port

但是,如果我在 client.connect 调用中强制 connecthost 为“127.0.0.1”,我的代码就可以正常工作。

我猜测 Windows 10 处理“0.0.0.0”的方式一定与 Linux 处理它的方式不同。如果是这样,那么也许 Windows 下的 sshtunnel.open_tunnel 应该更改为返回“127.0.0.1”而不是“0.0.0.0”。

无论如何,现在可以了。

关于Python paramiko/sshtunnel 代码在 Linux 下工作正常,但在 Windows 下失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67963602/

相关文章:

windows - Windows 与 Linux/UNIX 中 Perl 的 waitpid() 和 IPC::Open2

c# - 通过命令断开登录的远程桌面用户

ruby-on-rails - Rails 3 查询字符串

python - ttk:条目小部件禁用背景颜色

Python 搜索并打印值

python - 将 Python 中的 unix 时间戳转换为日期时间并落后 2 小时

python - 如何在后台运行进程并覆盖标准流

linux - 如何在 Mac OS X 默认终端上禁用来自 "bracketed paste mode"的奇怪字符?

python仍然无法插入数据库

linux - 触摸命令。没有权限