Skip to content Skip to sidebar Skip to footer

Ssh Tunnel From Python Is Closing Automatically

I need some advice about the structure of my program. I'm connecting to an external MySQL database using sshtunnel. It's now working correctly (I can issue SQL commands and get r

Solution 1:

As per steven-rumbalski's comment above:

Replace:with SSHTunnelForwarder(...) as serverWith:server = SSHTunnelForwarder(...)Then wrap:server.start()...server.stop() around the code you want to be sent via the SSH Tunnel.

Here is the converted code:

import pymysql, shlex, shutil, subprocess
import logging
import sshtunnel
from sshtunnel import SSHTunnelForwarder
import iot_config as cfg

defOpenSSHTunnel():
    global server
    sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG
    server = SSHTunnelForwarder(
        (cfg.sshconn['host'], cfg.sshconn['port']),
        ssh_username = cfg.sshconn['user'],
        ssh_private_key = cfg.sshconn['private_key_loc'],
        ssh_private_key_password = cfg.sshconn['private_key_passwd'],
        remote_bind_address = ('127.0.0.1', 3306)
    )

defOpenRemoteDB():
    global remotecur, remotedb
    remotedb = None
    remotedb = pymysql.connect(
        host='127.0.0.1',
        user=cfg.remotedbconn['user'],
        passwd=cfg.remotedbconn['passwd'],
        db=cfg.remotedbconn['db'],
        port=server.local_bind_port
    )
    remotecur = remotedb.cursor()
    print("Checkpoint 1")

defSyncActions():
    print("Checkpoint 2")
    # this should now work as expected
    remotecur.execute("SELECT ActionID, Description FROM cmAction")
    for r in remotecur:
        print(r)

# Main program starts here
OpenSSHTunnel()
server.start()
OpenRemoteDB()
SyncActions()
server.stop()

Post a Comment for "Ssh Tunnel From Python Is Closing Automatically"