【问题标题】:Python: Automatically reconnect ssh tunnel after remote server gone downPython:远程服务器关闭后自动重新连接 ssh 隧道
【发布时间】:2018-05-11 21:19:08
【问题描述】:

我已经实现了一个在 Python 中建立 ssh 隧道的功能,所以我可以在 NAT 后面的数据库中插入数据(没有可用的端口转发)。

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()

现在,这工作得很好。通过此实现,我稍后将在localhost:localport 上建立与数据库的连接(localportfnc_ssh_tunnel() 返回)。

如果由于某种原因,数据库所在的远程 PC 重新启动,则会出现问题。如果是这样,PC 上的 SSH 服务器将断开所有连接,因此我的 ssh-tunnel 也会断开。

要从这种情况中恢复,我需要重新启动 Python 程序:这样,隧道将重新建立。

如果远程服务器宕机->up,是否有一种重新建立 ssh 隧道的巧妙方法?

谢谢!

【问题讨论】:

    标签: python-3.x paramiko ssh-tunnel reconnect


    【解决方案1】:

    我遇到了同样的问题,这是我的解决方案:

    启动服务器后,继续检查服务器是否处于活动状态,如果没有,则重新启动。

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 1970-01-01
      • 2013-08-09
      • 2016-02-13
      • 2014-05-03
      • 2017-01-01
      • 2020-07-05
      • 1970-01-01
      • 2017-09-27
      相关资源
      最近更新 更多