Skip to main content

Pure python SSH tunnels

Project description

CircleCI AppVeyor Documentation Status coveralls version

pyversions license

Author: Pahaz Blinov

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

Inspired by https://github.com/jmagnusson/bgtunnel, but it 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(
    'pahaz.urfuclub.ru',
    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),
    block_on_close=False
) 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',
        block_on_close=False
    ) 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 [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 [FOLDER ...]]]
                 ssh_address

Pure python ssh tunnel utils
Version 0.1.5

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

optional arguments:
  -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 [IP:PORT ...]], --local_bind_address [IP:PORT [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 [FOLDER ...]], --host_pkey_directories [FOLDER [FOLDER ...]]
                        List of directories where SSH pkeys (in the format `id_*`) may be found

Online documentation

Documentation may be found at readthedocs.

CONTRIBUTORS

CHANGELOG

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sshtunnel-0.1.5.tar.gz (49.3 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

sshtunnel-0.1.5-py3.8.egg (22.6 kB view details)

Uploaded Egg

sshtunnel-0.1.5-py3.7.egg (22.6 kB view details)

Uploaded Egg

sshtunnel-0.1.5-py3.6.egg (22.6 kB view details)

Uploaded Egg

sshtunnel-0.1.5-py3.5.egg (22.6 kB view details)

Uploaded Egg

sshtunnel-0.1.5-py3.4.egg (22.6 kB view details)

Uploaded Egg

sshtunnel-0.1.5-py2.py3-none-any.whl (23.3 kB view details)

Uploaded Python 2Python 3

sshtunnel-0.1.5-py2.7.egg (22.6 kB view details)

Uploaded Egg

File details

Details for the file sshtunnel-0.1.5.tar.gz.

File metadata

  • Download URL: sshtunnel-0.1.5.tar.gz
  • Upload date:
  • Size: 49.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.19.1 setuptools/40.0.0 requests-toolbelt/0.9.1 tqdm/4.25.0 CPython/3.7.3

File hashes

Hashes for sshtunnel-0.1.5.tar.gz
Algorithm Hash digest
SHA256 c813fdcda8e81c3936ffeac47cb69cfb2d1f5e77ad0de656c6dab56aeebd9249
MD5 8c781366ebfc5e5146d6dc36a9fa5b84
BLAKE2b-256 c55c4b320d7ec4b0d5d4d6df1fdf66a5799625b3623d0ce4efe81719c6f8dfb3

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py3.8.egg.

File metadata

  • Download URL: sshtunnel-0.1.5-py3.8.egg
  • Upload date:
  • Size: 22.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.6

File hashes

Hashes for sshtunnel-0.1.5-py3.8.egg
Algorithm Hash digest
SHA256 fb2e721c764e3daf7f087dfb52f3cce903b60f092babcd3edbe82fd7ca508ede
MD5 e025ab100d30faf9b43579d2e94b22fc
BLAKE2b-256 12113d2a67287323cb8f78de49ea8b9717d127baef441e9da5b903f9cc63f17b

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py3.7.egg.

File metadata

  • Download URL: sshtunnel-0.1.5-py3.7.egg
  • Upload date:
  • Size: 22.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.7.9

File hashes

Hashes for sshtunnel-0.1.5-py3.7.egg
Algorithm Hash digest
SHA256 224b0b8b3d3fa043934b3823365ff396fd2b8cb3822649cc43d6a203751225a0
MD5 d20f2500bf4410c52ec530371f08f3f4
BLAKE2b-256 621d45eddd26616ac97842bb42fe6db2424139656620b7dd064dbfc5c6450242

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py3.6.egg.

File metadata

  • Download URL: sshtunnel-0.1.5-py3.6.egg
  • Upload date:
  • Size: 22.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.6.12

File hashes

Hashes for sshtunnel-0.1.5-py3.6.egg
Algorithm Hash digest
SHA256 18cfe4c95d435f48ce71b5e087b64861b7ce0bee0affb0394d0ebcbb432036e9
MD5 78cc71e2ec506bdfa576bc7fecd04cf1
BLAKE2b-256 3e8669ae3fc32ecd2e10b9a9061c43eb690a8f99bde3c32b18057db706ba57fb

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py3.5.egg.

File metadata

  • Download URL: sshtunnel-0.1.5-py3.5.egg
  • Upload date:
  • Size: 22.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.5.10

File hashes

Hashes for sshtunnel-0.1.5-py3.5.egg
Algorithm Hash digest
SHA256 625ad4c3fdfa76152e66b7e09364479da364be932158d20bcabfb887fd680c38
MD5 c750d9c681255001339498fdbebcf195
BLAKE2b-256 40a093f94ac4603cdbfd72652ea7f288895a16bcf94a2193901ca0c957a5c431

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py3.4.egg.

File metadata

  • Download URL: sshtunnel-0.1.5-py3.4.egg
  • Upload date:
  • Size: 22.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/43.0.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.4.10

File hashes

Hashes for sshtunnel-0.1.5-py3.4.egg
Algorithm Hash digest
SHA256 a60834ba3226f6695d72eb73ceff9275179b660d0103f6824d1610581b519f36
MD5 0937c6df2eda8ce1818d3a03a5082a37
BLAKE2b-256 c81d972f3190dcad06fc6dccadb480c630b08e1162f71eeba904a828c6f00669

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py2.py3-none-any.whl.

File metadata

  • Download URL: sshtunnel-0.1.5-py2.py3-none-any.whl
  • Upload date:
  • Size: 23.3 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.6

File hashes

Hashes for sshtunnel-0.1.5-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 5eee2e414c3fd9e9ef5d058bebece272a6aae928849ef7f2d9561b7fffab7aea
MD5 f3b52a2dfe77838ecbc383516765a74e
BLAKE2b-256 387d6f19be1ee49cee9593c5ac3aa1fb38fe30eaf1520114e08dee2ab2a45855

See more details on using hashes here.

File details

Details for the file sshtunnel-0.1.5-py2.7.egg.

File metadata

  • Download URL: sshtunnel-0.1.5-py2.7.egg
  • Upload date:
  • Size: 22.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/44.1.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/2.7.18

File hashes

Hashes for sshtunnel-0.1.5-py2.7.egg
Algorithm Hash digest
SHA256 583b0e4cb80a2bc417b6443ebca77964709004059d598533b3c221c74078a0c7
MD5 04dca5994a6a24740f49a654f5ea9041
BLAKE2b-256 6e914b79edf8b523dc92d9b0238a223ab8cb8e6b22d592c6ea6c4e98ddc4c257

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page