如何使用 python 的 sshtunnel 连接到路由器 运行 only telnet?

How to use python's sshtunnel to connect to a router running only telnet?

我必须连接到一个 jumpserver 才能连接到一堆路由器 运行 只有 telnet。我是 SSH 隧道的新手,但我发现在我本地机器的命令行上,以下命令形成了必要的隧道:

$ ssh -fNL 2300:remote_host:23 user@jumpServer

然后我所要做的就是连接到本地计算机上的端口 2300,以便将流量转发到路由器上的端口 23(没有 SSH,只有 telnet):

> telnet localhost 2300

我有几个问题:

  1. 真正的隧道在哪里形成?正如我所说,路由器的端口 22 被阻止,即它不支持 运行 SSH。但是,我的本地机器和 gateway/jumpserver 可以。那么,如果隧道在我的本地机器和跳转服务器之间形成,那么跳转服务器和路由器之间的传输模式是什么?
  2. 如果我没理解错的话,我本地机器上的端口 2300 上有一个侦听器,它通过 SSH 隧道将所有流量转发到跳转服务器上的某个端口,然后再转发到路由器。正确的?
  3. [Python 具体问题] 如何让 sshtunnel 模块以编程方式执行此操作?我尝试了以下方法:
from sshtunnel import open_tunnel
from telnetlib import Telnet

js = '123.456.555.666'
js_usr = "user"
rem_host = '123.456.789.101'

with open_tunnel(
    ssh_address_or_host=(js, 22),
    ssh_username=js_usr,
    ssh_password="password",
    remote_bind_address=(rem_host, 23)
) as tunnel:
    with Telnet(js, tunnel.local_bind_port, 10) as tn:
        tn.interact()

但是,这会引发以下错误:

Traceback (most recent call last): File "C:/Users/somsinha/PycharmProjects/SysTEst/sshTunnelTest.py", line 14, in with Telnet(js, tunnel.local_bind_port, 10) as tn:

File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\telnetlib.py", line 218, in init self.open(host, port, timeout)

File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\telnetlib.py", line 234, in open self.sock = socket.create_connection((host, port), timeout)

File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\socket.py", line 727, in create_connection raise err

File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\socket.py", line 716, in create_connection sock.connect(sa)

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

如何手动制作pythonssh -fNL 2300:remote_host:23 user@jumpServer

你的代码一切正常,除了使用应该使用 "localhost" 和 telnet:

from sshtunnel import open_tunnel
from telnetlib import Telnet

js = '123.456.555.666'
js_usr = "user"
rem_host = '123.456.789.101'

with open_tunnel(
    ssh_address_or_host=(js, 22),
    ssh_username=js_usr,
    ssh_password="password",
    remote_bind_address=(rem_host, 23)
) as tunnel:
   # Use localhost as host
    with Telnet('localhost', tunnel.local_bind_port, 10) as tn:
        tn.interact()

原因是端口转​​发到本地主机,必须从本地主机访问。