python - 来自 Python 的 SSH 隧道自动关闭

标签 python mysql python-3.x ssh

我需要一些关于程序结构的建议。我正在使用 sshtunnel 连接到外部 MySQL 数据库.它现在可以正常工作(我可以发出 SQL 命令并获得结果),但前提是这些命令与打开连接的功能相同。如果它们处于不同的功能,隧道会在我使用之前自动关闭。 (见下面的代码 - 它在两个检查点之间关闭。)所以我的问题是:

  1. 我是否应该在每次使用时检查连接是否打开?我该怎么做?
  2. 如何使用来自不同功能的连接?我在 sshtunnel 中看到了一个名为“keepalive”的属性(它将在指定的时间长度内保持连接打开)——这是我需要的吗?我该如何使用它?
  3. 我可以忘记手动关闭隧道吗?
  4. 还有什么可以帮助我完成这项工作的吗?您可能会说,我是这个主题的新手!

谢谢。

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

输出:

2016-10-06 12:34:21,088| WAR | MainThrea/0954@sshtunnel | Could not read SSH configuration file: ~/.ssh/config
2016-10-06 12:34:21,153| INF | MainThrea/0981@sshtunnel | 0 keys loaded from agent
2016-10-06 12:34:21,963| DEB | MainThrea/1160@sshtunnel | Private key file (/etc/ssh/lavenham_private_key.key, <class 'paramiko.rsakey.RSAKey'>) successfully loaded
2016-10-06 12:34:22,003| INF | MainThrea/0901@sshtunnel | Connecting to gateway: lavenham.co.uk:22 as user 'lavenham'
2016-10-06 12:34:22,062| DEB | MainThrea/0904@sshtunnel | Concurrent connections allowed: True
2016-10-06 12:34:22,117| DEB | MainThrea/1300@sshtunnel | Trying to log in with key: b'611711d06f2b671960c3458d25ca3c20'
2016-10-06 12:34:23,083| INF | Srv-39033/1334@sshtunnel | Opening tunnel: 0.0.0.0:39033 <> 127.0.0.1:3306
Checkpoint 1
2016-10-06 12:34:23,290| INF | MainThrea/1350@sshtunnel | Shutting down tunnel ('0.0.0.0', 39033)
2016-10-06 12:34:23,424| INF | Srv-39033/1340@sshtunnel | Tunnel: 0.0.0.0:39033 <> 127.0.0.1:3306 released
2016-10-06 12:34:23,426| DEB | MainThrea/1363@sshtunnel | Transport is closed
Checkpoint 2
Traceback (most recent call last):
  File "/home/pi/Documents/iot_pm2/2016-10-06.py", line 33, in <module>
    SyncActions()
  File "/home/pi/Documents/iot_pm2/2016-10-06.py", line 27, in SyncActions
    remotecur.execute("SELECT ActionID, Description FROM cmAction")
  File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 146, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 296, in _query
    conn.query(q)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 819, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 1001, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 1285, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 945, in _read_packet
    packet_header = self._read_bytes(4)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 981, in _read_bytes
    2013, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

最佳答案

根据 steven-rumbalski上面的评论:

替换: 以 SSHTunnelForwarder(...) 作为服务器
使用: server = SSHTunnelForwarder(...)
然后换行: server.start() ... server.stop()
围绕您要通过 SSH 隧道发送的代码。

下面是转换后的代码:

import pymysql, shlex, shutil, subprocess
import logging
import sshtunnel
from sshtunnel import SSHTunnelForwarder
import iot_config as cfg

def OpenSSHTunnel():
    global server
    sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG
    server = 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)
    )

def OpenRemoteDB():
    global remotecur, remotedb
    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")

def SyncActions():
    print("Checkpoint 2")
    # this should now work as expected
    remotecur.execute("SELECT ActionID, Description FROM cmAction")
    for r in remotecur:
        print(r)

# Main program starts here
OpenSSHTunnel()
server.start()
OpenRemoteDB()
SyncActions()
server.stop()

关于python - 来自 Python 的 SSH 隧道自动关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39921388/

相关文章:

python 并在方法中使用 'self'

php - 获取表中跨列的记录的总大小 - symfony

python-3.x - 以最少的数据库查询次数保存(最小化保存方法调用)

python-3.x - 从字典中删除值

python - 除了显示之外,打印功能实际上做了什么?

python - 添加边会创建重复节点,而不是使用已添加的节点

Python Asyncio 任务在没有 gather() 的情况下运行

python - 如何将阿拉伯语文本放入txt文件中

php - 使用 MySQL 进行土耳其语字符编码

mysql - 对唯一字段对求和的 SQL 语句