如何使用Python SSHTunnle转发多个端口

问题描述 投票:0回答:1

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

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/

在example1&2中,我只能指定一个远程与本地绑定地址。不确定如何连接多台服务器(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程序包。

python ssh-tunnel
1个回答
0
投票

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

有绑定的单数形式(local_bind_addressremote_bind_address,有复数的绑定形式(local_bind_addressesremote_bind_addresses

单数版本期望tuple包含用于连接的变量,而复数版本期望list为一个或多个tuple(s)

这里是示例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地址/端口将彼此对应。

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

[连接:172.16.0.1端口:80,通过以下通道建立隧道:127.0.0.1端口:1180

连接:172.16.0.2端口:22,通过以下通道传输:127.0.0.1端口:10022

© www.soinside.com 2019 - 2024. All rights reserved.