6

I need to tunnel with SSH to get access to the database. After creating the tunnel in Python code with sshtunnel (https://github.com/pahaz/sshtunnel/), the script hangs, no further commands are being executed. The last print I see from the provided code is local_bind_port. Everything after is stuck. Have I misunderstood some basic principle?

When I create the tunnel manually via the cmd line the db connection works fine in a separate python script.

System: Python 3.6.1, sshtunnel 0.1.2, macOS 10.12, Server is CentOS 7

Python code:

import pymysql.cursors
import sshtunnel

with SSHTunnelForwarder(
        ('gateway_host', gateway_port),
        ssh_username='ssh_username',
        ssh_pkey='/path/to/id_rsa',
        ssh_private_key_password='pw',
        remote_bind_address=('remote_bind', 3306),
        local_bind_address=('127.0.0.1', 3306),
        logger=create_logger(loglevel=1)
) as tunnel:
    print('Establishing connection')

    print('tunnel_bindings:', tunnel.tunnel_bindings)
    print('tunnel_is_up:', tunnel.tunnel_is_up)
    print('local_bind_port:', tunnel.local_bind_port)

    connection = pymysql.connect(host='127.0.0.1',
                                 port=3306,
                                 user='db_username',
                                 password='db_password',
                                 db='db_name',
                                 cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            sql = '''SELECT VERSION();'''
            cursor.execute(sql)
            result = cursor.fetchall()
            print(result)
    finally:
        connection.close()

    print('Finish')

Log output (after last line it gets stuck):

2017-07-26 22:42:37,788| INF |  Srv-3306/1318@sshtunnel | Opening tunnel: 127.0.0.1:3306 <> remote_bind:3306
tunnel_bindings: {('remote_bind', 3306): ('127.0.0.1', 3306)}
tunnel_is_up: {('127.0.0.1', 3306): True}
local_bind_port: 3306
2017-07-26 22:42:37,864| TRA |  Thread-3/0347@sshtunnel | #1 <-- ('127.0.0.1', 63007) connected


Manual SSH Tunnel which is working:

ssh -L 3306:remote_bind:3306 ssh_username@gateway_host -p gateway_port -N

Thanks for your help

Jim B
  • 641
  • 5
  • 18

0 Answers0