4

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

This is the command I am using in shell:

ssh user@remote_server -L 2443:localhost:433

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

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)

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

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.

0

1 Answer 1

1

You can try this example: 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.