Python: Automatically reconnect ssh tunnel after remote server gone down

匆匆过客 提交于 2021-02-19 05:32:30

问题


I have implemented a function to establish an ssh-tunnel in Python, so I can insert data in a DB behind a NAT (no port forwarding available).

import paramiko
from sshtunnel import SSHTunnelForwarder
def fnc_ssh_tunnel():
    try:
        sshServer = SSHTunnelForwarder(
                (SSH_IP, SSH_PORT),
                ssh_username            = SSH_USER,
                ssh_password            = SSH_PASS,
                set_keepalive           = float(SSH_KEEP_ALIVE),
                remote_bind_address     = (DB_IP, DB_PORT),
            )
        sshServer.start()
        localPort = sshServer.local_bind_port
        logPrint("SSH Tunnel Started to " + str(sshServer.tunnel_bindings), DEBUG_ID)
        sshServer.check_tunnels()
        return localPort

    except Exception as e:

        logPrint("Error SSH Tunnel", DEBUG_ID)
        logPrint(e,DEBUG_ID)
        quit()

Now, this is working very well. With this implementation I will later bring up a connection to the DB on localhost:localport (localport being returned by fnc_ssh_tunnel()).

The problem arises if for some reason, the remote PC where the DB resides, reboots. If so, the SSH server on the PC will tear all the connections down and hence also my ssh-tunnel will go down.

To recover from that situation, I need to restart the Python program: with this, the tunnel will reestablish.

Is there a neat way of reestablishing the ssh-tunnel if the remote server went down->up?

Thanks!


回答1:


I am facing the same problem, and here is my solution :

After starting the server, keep checking if the server is active, if it's not, start it again.

def get_server():
    # define ssh server and return it

server = get_server()
server.start()
while True :
    if(server.is_active):
        print("alive... " + (time.ctime()))
    else:
        print("reconnecting... " + time.ctime())
        server.stop()
        server = get_server()
        server.start()
    time.sleep(60)


来源:https://stackoverflow.com/questions/47531204/python-automatically-reconnect-ssh-tunnel-after-remote-server-gone-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!