python-3.x - python : Automatically reconnect ssh tunnel after remote server gone down

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

我已经在 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 隧道也将断开。

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

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

谢谢!

最佳答案

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

启动服务器后,不断检查服务器是否处于事件状态,如果没有,请重新启动。

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)

关于python-3.x - python : Automatically reconnect ssh tunnel after remote server gone down,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531204/

相关文章:

C# SSH 隧道 Postgres 数据库连接

python-3.x - 如何在 fritzconnect 中发送 call_action

python - 在某些字符之后分割字符串?

python - Kubernetes Python 客户端 : update deployment spec with affinity

Python Paramiko(客户端)多重身份验证

python - SSH - 带有 paramiko 问题的 Python

SSH远程端口转发指定接口(interface)

mongodb - 如何通过 ssh 隧道将数据保存到远程 mongoDB? (拒绝连接)

python - 测试请求身份验证

python - paramiko ls 有几个文件输出被截断