我已经成功地使以下python paramiko/sshtunnel代码在linux下正常工作,以便通过SSH隧道到远程机器上的端口。但是,在Windows10下运行完全相同的python代码会失败。这两种情况下都是Python3.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'和connectport
的随机值:但是,如果我在
client.connect
调用中强制connecthost
为'127.0.0.1',我的代码工作正常我猜Windows10处理“0.0.0.0”的方式必须与linux处理“0.0.0.0”的方式不同。如果是这样,那么可能应该将Windows下的
sshtunnel.open_tunnel
更改为返回“127.0.0.1”而不是“0.0.0.0”不管怎么说,这现在起作用了
相关问题 更多 >
编程相关推荐