我已经在 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
上建立与数据库的连接(localport
由 fnc_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/