python - Python中的双SSH隧道
问题描述
今天我在命令行中使用 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 包,但它只能帮助我进行一个端口转发而不是双重。
解决方案
你可以试试这个例子:https ://github.com/pahaz/sshtunnel#example-4
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)
推荐阅读
- c# - 如何在 c# 中正确地将主键分配给 DataTable?
- visual-studio-code - 有没有办法使用另一个扩展名而不是.feature?
- python - 如何在内部模块odoo(例如CRM)中添加菜单项继承?
- c# - 如何正确实现泛型接口方法?
- java - 我想通过调用 API 来获取用户的数组值
- selenium - 如何使用 IntelliJ 从 Selenium/Junit java 文件制作可执行 jar 文件?
- swift - 无法修复 Leaks Tool 指向的泄漏
- android - 以编程方式将事件添加到日历
- json - 在使用 React Native 的某些记录后无法将值保存到 localMongoDB
- android - 如何将 android 模块用作应用程序和库