Skip to content

Sshtunnel

The sshtunnel library simplifies SSH tunneling by wrapping paramiko.

Install

pip install sshtunnel

Example

Forward Remote MySQL Port to Localhost:

from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    ('ssh.example.com', 22),  # SSH server and port
    ssh_username='your_username',
    ssh_password='your_password',  # or use `ssh_pkey='/path/to/private.key'`
    remote_bind_address=('127.0.0.1', 3306),  # Remote DB server and port
    local_bind_address=('127.0.0.1', 10022)   # Local port you’ll use
)

server.start()

print(f"Tunnel opened: {server.local_bind_host}:{server.local_bind_port}")

# Use this address for connecting to the DB:
# e.g., with pymysql or sqlalchemy:
# pymysql.connect(host='127.0.0.1', port=server.local_bind_port, ...)

# Don't forget to stop the server when done
server.stop()

See also