我需要一些关于我计划结构的建议。我正在使用sshtunnel连接到外部MySQL数据库。它现在可以正常工作了(我可以发出SQL命令并获得结果),但前提是这些命令与打开连接的功能相同。如果他们在不同的功能,隧道自动关闭之前,我可以使用它。(参见下面的代码-它在两个检查点之间关闭。)所以我的问题是:
谢谢。在
Python脚本:
import pymysql, shlex, shutil, subprocess
import logging
import sshtunnel
from sshtunnel import SSHTunnelForwarder
import iot_config as cfg
def OpenRemoteDB():
global remotecur, remotedb
sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG
with SSHTunnelForwarder(
(cfg.sshconn['host'], cfg.sshconn['port']),
ssh_username = cfg.sshconn['user'],
ssh_private_key = cfg.sshconn['private_key_loc'],
ssh_private_key_password = cfg.sshconn['private_key_passwd'],
remote_bind_address = ('127.0.0.1', 3306)) as server:
remotedb = None
remotedb = pymysql.connect(host='127.0.0.1', user=cfg.remotedbconn['user'], passwd=cfg.remotedbconn['passwd'], db=cfg.remotedbconn['db'], port=server.local_bind_port)
remotecur = remotedb.cursor()
print("Checkpoint 1")
#The next three lines work fine
# remotecur.execute("SELECT ActionID, Description FROM cmAction")
# for r in remotecur:
# print(r)
def SyncActions():
print("Checkpoint 2")
#the next three lines don't work (because the connection has closed)
remotecur.execute("SELECT ActionID, Description FROM cmAction")
for r in remotecur:
print(r)
# Main program starts here
OpenRemoteDB()
SyncActions()
输出:
^{pr2}$
根据steven-rumbalski的评论:
替换:
with SSHTunnelForwarder(...) as server
使用:
server = SSHTunnelForwarder(...)
然后包装:
server.start()
...
server.stop()
关于您希望通过SSH隧道发送的代码。在
以下是转换后的代码:
相关问题 更多 >
编程相关推荐