我已经实现了一个在 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 隧道?
Thanks!