Published on

Setup a SSH Tunnel with the sshtunnel module in Python


Sometimes we need to restrict access to a port, where a port should listen on localhost, but you want to access that port from a remote source. One secure way of doing that, is to establish a SSH Tunnel to the remote side, and forward to port via the SSH Tunnel.

Today we will setup a Flask Web Service on our Remote Server (Side B) which will be listening on and setup the SSH Tunnel with the sshtunnel module in Python from our client side (Side A). Then we will make a GET request on our client side to the port that we are forwarding via the tunnel to our remote side.


Remote Side:

Our Demo Python Flask Application:

from flask import Flask

app = Flask(__name__)

def index():
    return 'OK'

if __name__ == '__main__':'', port=5000)

Run the server:

$ python
Listening on

Client Side:

From our client side we first need to install sshtunnel via pip:

$ pip install sshtunnel requests --user

Our code for our client that will establish the tunnel and do the GET request:

from sshtunnel import SSHTunnelForwarder
import requests

remote_user = 'ubuntu'
remote_host = ''
remote_port = 22
local_host = ''
local_port = 5000

server = SSHTunnelForwarder(
   (remote_host, remote_port),
   remote_bind_address=(local_host, local_port),
   local_bind_address=(local_host, local_port),


headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'}
r = requests.get('', headers=headers).content

Running our app:

$ python

So we have sucessfully established our ssh tunnel to our remote side, and able to access the network restricted port via the tunnel.


Thank You

Thanks for reading, feel free to check out my website, and subscribe to my newsletter or follow me at @ruanbekker on Twitter.

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.

Buy Me A Coffee