python中的双SSH隧道

python中的双SSH隧道,python,ssh,paramiko,ssh-tunnel,Python,Ssh,Paramiko,Ssh Tunnel,今天,我在命令行中使用ssh将端口从远程服务器转发到本地机器,使用中间服务器 这是我在shell中使用的命令: ssh user@remote_server -L 2443:localhost:433 此ssh会话使用ssh配置文件发出多跳: Host intermediate_server IdentityFile "google_compute_engine" Host remote_server ProxyCommand ssh user@interme

今天,我在命令行中使用ssh将端口从远程服务器转发到本地机器,使用中间服务器

这是我在shell中使用的命令:

ssh user@remote_server -L 2443:localhost:433
此ssh会话使用ssh配置文件发出多跳:

Host intermediate_server
   IdentityFile "google_compute_engine"

Host remote_server
   ProxyCommand ssh user@intermediate_server -W %h:%p
ssh命令要求输入中间服务器(使用计算引擎密钥)和远程服务器(不同密码)的密码 输入密码后,此代码起作用:

import requests
import pandas as pd
from requests.auth import HTTPBasicAuth

url = 'https://localhost:2443/my_site'
my_ds = requests.get(url, auth=HTTPBasicAuth('user', 'password'), verify=False)
print pd.read_json(my_ds.content)
但是,我只能在命令行中使用手动ssh隧道使其工作

在python中,如何使用密钥、用户名和密码启动双通道?
我尝试使用sshtunnel包,但它只帮助我进行单端口转发,而不是双端口转发。

您可以尝试以下示例:

import sshtunnel
import requests
import pandas as pd
from requests.auth import HTTPBasicAuth

with sshtunnel.open_tunnel(
    ssh_address_or_host=('remote_server', 22),
    ssh_username="user",
    remote_bind_address=('intermediate_server', 22),
    block_on_close=False
) as tunnel1:
    print('Connection to tunnel1 (intermediate_server) OK...')
    with sshtunnel.open_tunnel(
        ssh_address_or_host=('127.0.0.1', tunnel1.local_bind_port),
        remote_bind_address=('127.0.0.1', 2443),
        ssh_username='user',
        ssh_password='intermediate_server_pwd',
        block_on_close=False
    ) as tunnel2:
        url = 'https://localhost:'+tunnel2.local_bind_port+'/my_site'
        my_ds = requests.get(url, auth=HTTPBasicAuth('user', 'password'), verify=False)
        print(my_ds.content)