本文介绍了Python 中的双 SSH 隧道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Today I am using ssh in command line to forward ports from a remote server, using an intermediate server to my local machine.

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

This is the command I am using in shell:

ssh user@remote_server -L 2443:localhost:433

这个 ssh 会话使用 ssh 配置文件来发出多跳:

This ssh session uses the ssh config file to issue the multi hop:

Host intermediate_server
   IdentityFile "google_compute_engine"

Host remote_server
   ProxyCommand ssh user@intermediate_server -W %h:%p

ssh 命令需要为中间服务器(使用计算引擎密钥)和远程服务器(不同的密码)输入密码输入密码后,此代码有效:

The ssh command requires entering a password both for the intermediate server (using a compute engine key) and the remote server (different passwords)After entering the passwords, this code works:

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 隧道使其工作.

However, I could only get it to work using the manual ssh tunnel in the command line.

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

How do I initiate a double tunnel with a key, a username and a password in python?I tried to use the sshtunnel package, but it only helps me with one port forwarding and not a double.

推荐答案

你可以试试这个例子: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)

这篇关于Python 中的双 SSH 隧道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:14