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

Python paramiko/sshtunnel code works fine under linux but fails under Windows

我已成功获得以下 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 Whosebug 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 下,我可以在 Shell 程序处于 运行ning 时进入 Power Shell,并且我可以 运行接下来,在这种情况下,我确实连接到了端口并看到了远程数据...

telnet localhost 53906

这似乎暗示 python 尝试连接到导致错误的套接字的方式有问题。

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

非常感谢。

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

这两行return 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 必须以不同于 linux 的方式处理“0.0.0.0”。如果是这样,那么也许 Windows 下的 sshtunnel.open_tunnel 应该更改为 return '127.0.0.1' 而不是 '0.0.0.0'。

无论如何,现在可以使用了。