• Stars
    star
    1,224
  • Rank 38,318 (Top 0.8 %)
  • Language
    Python
  • License
    MIT License
  • Created over 10 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SSH tunnels to remote server.

CircleCI AppVeyor Documentation Status coveralls version

pyversions license

Author: Pahaz

Repo: https://github.com/pahaz/sshtunnel/

Inspired by https://github.com/jmagnusson/bgtunnel, which doesn't work on Windows.

See also: https://github.com/paramiko/paramiko/blob/master/demos/forward.py

Requirements

Installation

sshtunnel is on PyPI, so simply run:

pip install sshtunnel

or

easy_install sshtunnel

or

conda install -c conda-forge sshtunnel

to have it installed in your environment.

For installing from source, clone the repo and run:

python setup.py install

Testing the package

In order to run the tests you first need tox and run:

python setup.py test

Usage scenarios

One of the typical scenarios where sshtunnel is helpful is depicted in the figure below. User may need to connect a port of a remote server (i.e. 8080) where only SSH port (usually port 22) is reachable.

----------------------------------------------------------------------

                            |
-------------+              |    +----------+
    LOCAL    |              |    |  REMOTE  | :22 SSH
    CLIENT   | <== SSH ========> |  SERVER  | :8080 web service
-------------+              |    +----------+
                            |
                         FIREWALL (only port 22 is open)

----------------------------------------------------------------------

Fig1: How to connect to a service blocked by a firewall through SSH tunnel.

If allowed by the SSH server, it is also possible to reach a private server (from the perspective of REMOTE SERVER) not directly visible from the outside (LOCAL CLIENT's perspective).

----------------------------------------------------------------------

                            |
-------------+              |    +----------+               +---------
    LOCAL    |              |    |  REMOTE  |               | PRIVATE
    CLIENT   | <== SSH ========> |  SERVER  | <== local ==> | SERVER
-------------+              |    +----------+               +---------
                            |
                         FIREWALL (only port 443 is open)

----------------------------------------------------------------------

Fig2: How to connect to PRIVATE SERVER through SSH tunnel.

Usage examples

API allows either initializing the tunnel and starting it or using a with context, which will take care of starting and stopping the tunnel:

Example 1

Code corresponding to Fig1 above follows, given remote server's address is pahaz.urfuclub.ru, password authentication and randomly assigned local bind port.

from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    'alfa.8iq.dev',
    ssh_username="pahaz",
    ssh_password="secret",
    remote_bind_address=('127.0.0.1', 8080)
)

server.start()

print(server.local_bind_port)  # show assigned local port
# work with `SECRET SERVICE` through `server.local_bind_port`.

server.stop()

Example 2

Example of a port forwarding to a private server not directly reachable, assuming password protected pkey authentication, remote server's SSH service is listening on port 443 and that port is open in the firewall (Fig2):

import paramiko
import sshtunnel

with sshtunnel.open_tunnel(
    (REMOTE_SERVER_IP, 443),
    ssh_username="",
    ssh_pkey="/var/ssh/rsa_key",
    ssh_private_key_password="secret",
    remote_bind_address=(PRIVATE_SERVER_IP, 22),
    local_bind_address=('0.0.0.0', 10022)
) as tunnel:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('127.0.0.1', 10022)
    # do some operations with client session
    client.close()

print('FINISH!')

Example 3

Example of a port forwarding for the Vagrant MySQL local port:

from sshtunnel import open_tunnel
from time import sleep

with open_tunnel(
    ('localhost', 2222),
    ssh_username="vagrant",
    ssh_password="vagrant",
    remote_bind_address=('127.0.0.1', 3306)
) as server:

    print(server.local_bind_port)
    while True:
        # press Ctrl-C for stopping
        sleep(1)

print('FINISH!')

Or simply using the CLI:

(bash)$ python -m sshtunnel -U vagrant -P vagrant -L :3306 -R 127.0.0.1:3306 -p 2222 localhost

Example 4

Opening an SSH session jumping over two tunnels. SSH transport and tunnels will be daemonised, which will not wait for the connections to stop at close time.

import sshtunnel
from paramiko import SSHClient


with sshtunnel.open_tunnel(
    ssh_address_or_host=('GW1_ip', 20022),
    remote_bind_address=('GW2_ip', 22),
) as tunnel1:
    print('Connection to tunnel1 (GW1_ip:GW1_port) OK...')
    with sshtunnel.open_tunnel(
        ssh_address_or_host=('localhost', tunnel1.local_bind_port),
        remote_bind_address=('target_ip', 22),
        ssh_username='GW2_user',
        ssh_password='GW2_pwd',
    ) as tunnel2:
        print('Connection to tunnel2 (GW2_ip:GW2_port) OK...')
        with SSHClient() as ssh:
            ssh.connect('localhost',
                port=tunnel2.local_bind_port,
                username='target_user',
                password='target_pwd',
            )
            ssh.exec_command(...)

CLI usage

$ sshtunnel --help
usage: sshtunnel [-h] [-U SSH_USERNAME] [-p SSH_PORT] [-P SSH_PASSWORD] -R
                 IP:PORT [IP:PORT ...] [-L [IP:PORT ...]] [-k SSH_HOST_KEY]
                 [-K KEY_FILE] [-S KEY_PASSWORD] [-t] [-v] [-V] [-x IP:PORT]
                 [-c SSH_CONFIG_FILE] [-z] [-n] [-d [FOLDER ...]]
                 ssh_address

Pure python ssh tunnel utils
Version 0.4.0

positional arguments:
  ssh_address           SSH server IP address (GW for SSH tunnels)
                        set with "-- ssh_address" if immediately after -R or -L

options:
  -h, --help            show this help message and exit
  -U SSH_USERNAME, --username SSH_USERNAME
                        SSH server account username
  -p SSH_PORT, --server_port SSH_PORT
                        SSH server TCP port (default: 22)
  -P SSH_PASSWORD, --password SSH_PASSWORD
                        SSH server account password
  -R IP:PORT [IP:PORT ...], --remote_bind_address IP:PORT [IP:PORT ...]
                        Remote bind address sequence: ip_1:port_1 ip_2:port_2 ... ip_n:port_n
                        Equivalent to ssh -Lxxxx:IP_ADDRESS:PORT
                        If port is omitted, defaults to 22.
                        Example: -R 10.10.10.10: 10.10.10.10:5900
  -L [IP:PORT ...], --local_bind_address [IP:PORT ...]
                        Local bind address sequence: ip_1:port_1 ip_2:port_2 ... ip_n:port_n
                        Elements may also be valid UNIX socket domains:
                        /tmp/foo.sock /tmp/bar.sock ... /tmp/baz.sock
                        Equivalent to ssh -LPORT:xxxxxxxxx:xxxx, being the local IP address optional.
                        By default it will listen in all interfaces (0.0.0.0) and choose a random port.
                        Example: -L :40000
  -k SSH_HOST_KEY, --ssh_host_key SSH_HOST_KEY
                        Gateway's host key
  -K KEY_FILE, --private_key_file KEY_FILE
                        RSA/DSS/ECDSA private key file
  -S KEY_PASSWORD, --private_key_password KEY_PASSWORD
                        RSA/DSS/ECDSA private key password
  -t, --threaded        Allow concurrent connections to each tunnel
  -v, --verbose         Increase output verbosity (default: ERROR)
  -V, --version         Show version number and quit
  -x IP:PORT, --proxy IP:PORT
                        IP and port of SSH proxy to destination
  -c SSH_CONFIG_FILE, --config SSH_CONFIG_FILE
                        SSH configuration file, defaults to ~/.ssh/config
  -z, --compress        Request server for compression over SSH transport
  -n, --noagent         Disable looking for keys from an SSH agent
  -d [FOLDER ...], --host_pkey_directories [FOLDER ...]
                        List of directories where SSH pkeys (in the format `id_*`) may be found

More Repositories

1

bashtest

BashTest is a UNIX command-line tool for testing your bash/sh scripts
Python
45
star
2

Example-of-MVC-pattern-on-pure-Python-2015

MVC EXAMPLE
Python
37
star
3

static-site-paas

Simple static site PAAS based on `git push` / `git pull` (dokku compatible)
Shell
10
star
4

twitter-hadoop-example

Java example of analyzing twitter data with hadoop map reduce.
Java
9
star
5

django-geo-example

Python
7
star
6

RequireJS-example-of-use-lib-on-server-side-and-client-side

Small example how to use RequireJS lib on server-side (node.js) and client-side JavaScript code
JavaScript
4
star
7

py3line

Python
4
star
8

homework-simple-python-web-application

Repository for third homework of "Use Python in the Web" course.
Python
4
star
9

google-spreadsheets-api

Simple helper for google spreadsheet api
Python
3
star
10

drawio

2
star
11

pyandex_game

pyandex - карточная игра "пьяница" для компании yandex
JavaScript
2
star
12

cryptoassets

Python
2
star
13

cython-examples

How-to EMBED Python? How-to make Python faster? How-to make ANSI C Python extension?
Python
2
star
14

wflow

Shell build tool
Python
2
star
15

django-steps

Django lessens for students
Python
2
star
16

wikipedia-hadoop-example

Java example of analyzing wikipedia data with hadoop map reduce.
Java
2
star
17

django-smart-collectstatic

Smart Django collectstatic. Use Link and Copy for collecting static files
Python
2
star
18

empty

Empty repository example
2
star
19

git-receive

Python
2
star
20

Example-of-MVC-pattern-on-pure-Python-2014

Example for lectures. ASP.NET MVC on Python.
Python
2
star
21

python-regedit-replacer

Example work with python and regedit windows.
Python
1
star
22

my-new-startup

JavaScript
1
star
23

dbtask

1
star
24

django-tasks

1
star
25

django-2015-steps

Django first steps!
Python
1
star
26

open-node-js-edr

Secure one file easy to understand and install zero-dependent cross-platform Endpoint Detection & Response security tool
JavaScript
1
star
27

lesson2

Python
1
star
28

pyTesks

Some interesting
Python
1
star
29

Lessen1

Python WEB IMKN. Base WSGI application!
Python
1
star
30

FaceMash-flask

Example for "Use Python in the Web" cource.
Python
1
star
31

my-startup-monorepo

JavaScript
1
star
32

crawler

Multithread python crawler
Python
1
star
33

dokku-static-site

Just static dokku site
CSS
1
star
34

pahaz.8iq.dev

Pahaz blog
Astro
1
star