SoFunction
Updated on 2025-04-07

Sample code for implementing SSH tunneling function in Python

In modern network environments, it is becoming increasingly important to transfer data securely. SSH (Secure Shell) is a network protocol used to securely remotely log in to other computers. An SSH tunnel uses the SSH protocol to establish an encrypted channel to protect data transmitted through an insecure network. This article will introduce how to use Python to implement SSH tunneling.

1. Environmental preparation

1.1 Install the necessary libraries

To create an SSH tunnel using Python, you first need to install the paramiko library, a Python implementation for handling the SSH2 protocol. Can be installed via pip:

pip install paramiko

1.2 Prepare an SSH server

Make sure you have an SSH server that you can access and have permission to connect to that server via SSH. You need to know the server's IP address, port number, username and password or private key file.

2. Create an SSH tunnel

2.1 Basic Concept

SSH tunnels are divided into two types:

  • Local Tunnel: Forwards the local port to the remote host.
  • Remote tunnel: Forwards the remote port to the local host.

2.2 Create a local tunnel using Paramiko

Here is an example of creating a local SSH tunnel using paramiko that forwards the local port 8080 to port 80 on the remote server.

import paramiko
from sshtunnel import SSHTunnelForwarder
 
def create_ssh_tunnel(ssh_host, ssh_port, ssh_user, ssh_password, remote_bind_address, local_bind_address):
    # Create an SSH tunnel    server = SSHTunnelForwarder(
        (ssh_host, ssh_port),
        ssh_username=ssh_user,
        ssh_password=ssh_password,
        remote_bind_address=remote_bind_address,
        local_bind_address=local_bind_address
    )
    
    # Start SSH tunnel    ()
    print(f"SSH tunnel established: {local_bind_address[1]} -> {remote_bind_address}")
    return server
 
if __name__ == "__main__":
    # SSH server information    ssh_host = ''
    ssh_port = 22
    ssh_user = 'your_username'
    ssh_password = 'your_password'
    
    # Remote Service Information    remote_bind_address = ('localhost', 80)
    
    # Local listening address    local_bind_address = ('0.0.0.0', 8080)
    
    # Create an SSH tunnel    tunnel = create_ssh_tunnel(ssh_host, ssh_port, ssh_user, ssh_password, remote_bind_address, local_bind_address)
    
    try:
        # Keep the program running        while True:
            pass
    except KeyboardInterrupt:
        # Close the SSH tunnel        ()
        print("SSH tunnel closed.")

2.3 Create remote tunnels using Paramiko

The process of creating a remote tunnel is similar to a local tunnel, but in the opposite direction. Here is an example of forwarding the remote server's port 9000 to the local port 8080.

import paramiko
 
def create_remote_tunnel(ssh_host, ssh_port, ssh_user, ssh_password, remote_bind_address, local_bind_address):
    client = ()
    client.set_missing_host_key_policy(())
    (ssh_host, ssh_port, ssh_user, ssh_password)
    
    transport = client.get_transport()
    transport.request_port_forward('', remote_bind_address[1])
    
    def handler(chan, host, port):
        sock = ()
        try:
            ((host, port))
        except Exception as e:
            print('Forwarding request to %s:%d failed: %r' % (host, port, e))
            return
        print('Connected!  Tunnel open %r -> %r -> %r' % (chan.origin_addr, (), (host, port)))
        while True:
            r, w, x = ([sock, chan], [], [])
            if sock in r:
                data = (1024)
                if len(data) == 0:
                    break
                (data)
            if chan in r:
                data = (1024)
                if len(data) == 0:
                    break
                (data)
        ()
        ()
        print('Tunnel closed from %r' % (chan.origin_addr,))
    
    for i in range(transport.server_mode.port):
        transport.open_channel('direct-tcpip', local_bind_address, remote_bind_address, handler)
    
    try:
        while True:
            (1)
    except KeyboardInterrupt:
        print("Closing connections...")
        ()
        ()
 
if __name__ == "__main__":
    # SSH server information    ssh_host = ''
    ssh_port = 22
    ssh_user = 'your_username'
    ssh_password = 'your_password'
    
    # Remote Service Information    remote_bind_address = ('0.0.0.0', 9000)
    
    # Local listening address    local_bind_address = ('localhost', 8080)
    
    # Create a remote SSH tunnel    create_remote_tunnel(ssh_host, ssh_port, ssh_user, ssh_password, remote_bind_address, local_bind_address)

Through the above example, we can see that using Python and paramiko libraries to create SSH tunnels is very convenient. Whether it is a local tunnel or a remote tunnel, it can effectively help us safely transmit data in an unsafe network. Hope this article will help you!

3. Method supplement

An SSH tunnel is a secure way to establish encrypted communication channels between two network nodes. This is useful when remote access to the database, internal services, or when firewall restrictions need to be bypassed.

Here is a sample code to implement SSH tunneling using Python. We will use the paramiko library to create SSH connections and use the sshtunnel library to create the tunnel. First, you need to install these two libraries:

pip install paramiko sshtunnel

Suppose we have a remote server remote_server with an IP address of 192.168.1.100, an SSH port of 22, a username of ​​user, and a password of ​​password. We hope to access an internal database through this server, with the IP address of the database being ​​192.168.1.200 and the port being ​​3306.

Sample code

import pymysql
from sshtunnel import SSHTunnelForwarder
 
# SSH server informationssh_host = '192.168.1.100'
ssh_port = 22
ssh_username = 'user'
ssh_password = 'password'
 
# Target database informationdb_host = '192.168.1.200'
db_port = 3306
db_user = 'db_user'
db_password = 'db_password'
db_name = 'database_name'
 
# Create an SSH tunnelwith SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username=ssh_username,
    ssh_password=ssh_password,
    remote_bind_address=(db_host, db_port)
) as tunnel:
    # After the tunnel is successfully established, the local port is forwarded to the target database    local_port = tunnel.local_bind_port
    
    # Connect to the database    conn = (
        host='127.0.0.1',
        port=local_port,
        user=db_user,
        password=db_password,
        database=db_name
    )
    
    try:
        with () as cursor:
            # Execute SQL query            sql = "SELECT * FROM your_table"
            (sql)
            results = ()
            for row in results:
                print(row)
    finally:
        # Close the database connection        ()

Code explanation

  • Import library: Import pymysql​ and SSHTunnelForwarder​.
  • Define SSH and database information: Set up the relevant information about the SSH server and target database.
  • Create an SSH tunnel: Create an SSH tunnel using SSHTunnelForwarder. remote_bind_address​​ specifies the IP and port of the target database.
  • Connect to the database: Tunneling to the target database. Note that ​​127.0.0.1​​ and ​​local_port​ are used here because the tunnel maps the remote port to the local port.
  • Execute SQL query: Execute a simple SQL query and print the results.
  • Close the connection: Make sure to close the database connection after the operation is completed.

Things to note

  • Make sure the SSH server allows you to port forward.
  • If you use a key file instead of a password, you can replace ssh_password with ssh_pkey and specify the key file path.
  • Handle exceptions to ensure that the connection is properly closed in the event of an error.

Implementing SSH tunneling function in Python is usually used to securely connect to remote servers for database access, file transfer and other operations. The SSH tunnel can provide an encrypted channel to ensure the security of data transmission. The following details how to implement SSH tunneling using Python.

Using the paramiko library

paramiko​ is a very popular Python library for implementing the SSH2 protocol. It allows you to create SSH clients and servers and supports SSH tunneling.

Install paramiko​

First, you need to install the paramiko library. You can use ​​pip​​ to install:

pip install paramiko

Create an SSH tunnel

Here is a sample code showing how to create an SSH tunnel using paramiko:

import paramiko
from sshtunnel import SSHTunnelForwarder
 
# SSH server informationssh_host = 'your_ssh_server_ip'
ssh_port = 22
ssh_user = 'your_username'
ssh_password = 'your_password'
 
# Remote Service Informationremote_bind_address = ('127.0.0.1', 3306)  # Assume that the remote service is a MySQL database 
# Local binding addresslocal_bind_address = ('127.0.0.1', 10022)
 
# Create an SSH tunnelwith SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username=ssh_user,
    ssh_password=ssh_password,
    remote_bind_address=remote_bind_address,
    local_bind_address=local_bind_address
) as tunnel:
    print(f"SSH tunnel established: {local_bind_address} -> {remote_bind_address}")
    
    # Here, perform operations that need to be tunneled, such as connecting to the database    import pymysql
    
    db = (
        host='127.0.0.1',
        port=tunnel.local_bind_port,
        user='db_user',
        password='db_password',
        database='db_name'
    )
    
    cursor = ()
    ("SELECT * FROM your_table")
    results = ()
    for row in results:
        print(row)
    
    ()
 
print("SSH tunnel closed")

Code explanation

Import the library:

  • paramiko: for SSH connection.
  • ​​​SSHTunnelForwarder: Used to create SSH tunnels.

Configure SSH server information:

  • ssh_host​​: The IP address of the SSH server.
  • ssh_port: The port of the SSH server (default is 22).
  • ​​ssh_user​: The user name of the SSH server.
  • ​​ssh_password​: The password of the SSH server.

Configure remote service information:

remote_bind_address: The address and port of the remote service, such as the address and port of the MySQL database.

Configure the local binding address:

local_bind_address: locally bound address and port, used to listen for local connections.

Create an SSH tunnel:

  • Create an SSH tunnel using SSHTunnelForwarder.
  • ​​with​ statement ensures that the tunnel is automatically closed after use.

Perform an action:

  • After the tunnel is established, the remote service can be accessed through tunnel.local_bind_port.
  • In the example, use pymysql​ to connect to the MySQL database and execute a query.

Close the tunnel:

​​with​​ After the statement block is finished, the tunnel will be closed automatically.

Things to note

Make sure that the firewall on the SSH server allows connections from the local machine.

If you are authenticating with a key file instead of a password, you can specify the ssh_pkey parameter in SSHTunnelForwarder.

Handle exceptions such as network interruptions or authentication failures.

Through the above steps, you can easily create and manage SSH tunnels in Python to ensure the security and reliability of data transmission.

The above is the detailed content of the sample code for Python implementing SSH tunneling function. For more information about Python SSH tunneling function, please follow my other related articles!