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.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Roee Anuar
  • 3,071
  • 1
  • 19
  • 33

1 Answers1

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)
pahaz
  • 837
  • 9
  • 13