python - 如何使用Python SSHTunnel转发多个端口

标签 python ssh-tunnel

我需要转发到位于服务器后面的多个端口

server1(22) -> Server2(mysql, 3360) = local 3360
            -> Server3(http, 8080)  = local 8080
            -> Server4(oracle,1234) = local 1234

我只能通过 server1 访问 Server2、3 和 4。

我正在使用Python ssltunnel包https://pypi.org/project/sshtunnel/

在示例1&2中,我只能指定一个远程&本地绑定(bind)地址。 不知道如何连接多个服务器(2,3,4)

示例1

from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    'pahaz.urfuclub.ru',
    ssh_username="pahaz",
    ssh_password="secret",
    remote_bind_address=('127.0.0.1', 8080)
)

server.start()

print(server.local_bind_port)  # show assigned local port
# work with `SECRET SERVICE` through `server.local_bind_port`.

server.stop()

示例2

import paramiko
import sshtunnel

with sshtunnel.open_tunnel(
    (REMOTE_SERVER_IP, 443),
    ssh_username="",
    ssh_pkey="/var/ssh/rsa_key",
    ssh_private_key_password="secret",
    remote_bind_address=(PRIVATE_SERVER_IP, 22),
    local_bind_address=('0.0.0.0', 10022)
) as tunnel:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('127.0.0.1', 10022)
    # do some operations with client session
    client.close()

print('FINISH!')

我可以使用任何其他可以完成这项工作的 Python 包。

最佳答案

这两个示例都可以稍微修改以按照您想要的方式工作。

绑定(bind)有单数版本 (local_bind_address & remote_bind_address) 和复数版本绑定(bind) (local_bind_addresses & remote_bind_addresses.

单数版本需要一个包含连接变量的元组,而复数版本需要一个包含一个或多个元组列表 >.

这是示例 2 的修改版本:

import paramiko
import sshtunnel

tunnels = [("172.16.0.1", 80),
           ("172.16.0.2", 22)]

localPorts = [("127.0.0.1", 1180),
              ("127.0.0.1", 10022)]

with sshtunnel.open_tunnel(
    (REMOTE_SERVER_IP, 22),
    ssh_username="",
    ssh_pkey="/var/ssh/rsa_key",
    ssh_private_key_password="secret",
    remote_bind_addresses=tunnels,
    local_bind_addresses=localPorts
) as tunnel:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('127.0.0.1', 10022)
    # do some operations with client session
    client.close()

如果列表的长度相同,则 IP 地址/端口将彼此对应。

在上面的示例中,发生了以下情况:

Connection: 172.16.0.1 Port: 80, Is tunneled via: 127.0.0.1 Port: 1180

Connection: 172.16.0.2 Port: 22, Is tunneled via: 127.0.0.1 Port: 10022

关于python - 如何使用Python SSHTunnel转发多个端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60090438/

相关文章:

python - Dask 线程如何与 OpenBLAS/MKL/……交互?

docker - 从 Docker 容器显示 Android Studio GUI,同时通过 headless Ubuntu 服务器进行 SSH 隧道传输

python - 如何在 paramiko 中写入标准输入(从 exec_command 返回)?

python - Django 模型覆盖仅在我保存两次时才有效

python - 如何将 _io.TextIOWrapper 转换为字符串?

python - 带有 Paramiko exit while 循环的嵌套 SSH

java - 通过 JSch 的 SSH 隧道

java - 我无法使用 java 通过 ssh-tunnel 连接到数据库。

python - `Pool.*_async` 功能从未准备好

python - 使用executemany将CSV数据插入django模型