【发布时间】:2016-10-03 19:00:29
【问题描述】:
我正在通过 SSH 连接到远程 SQL 数据库。如果我从 Linux 命令行设置 SSH 连接(使用ssh-add my_private_key.key,然后使用ssh user@mysite.co.uk),连接时间不到一秒。但是,如果我使用sshtunnel(在以下脚本中)从 Python 执行此操作,则大约需要 70 秒。我接受使用 Python 可能有点开销,但不是那么多!特别是因为如果我在从命令行连接之后运行 Python 脚本,它会非常快。我需要在脚本中添加什么以使其更快?
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:
print("OK")
# Main program starts here
OpenRemoteDB()
Python 输出:
2016-09-20 12:34:15,272 | WARNING | Could not read SSH configuration file: ~/.ssh/config
2016-09-20 12:34:15,305 | INFO | 0 keys loaded from agent
2016-09-20 12:34:15,332 | DEBUG | Private key file (/etc/ssh/my_private_key.key, <class 'paramiko.rsakey.RSAKey'>) successfully loaded
2016-09-20 12:34:15,364 | INFO | Connecting to gateway: mysite.co.uk:22 as user 'user'
2016-09-20 12:34:15,389 | DEBUG | Concurrent connections allowed: True
2016-09-20 12:34:15,409 | DEBUG | Trying to log in with key: b'XXX'
2016-09-20 12:35:26,610 | INFO | Opening tunnel: 0.0.0.0:34504 <> 127.0.0.1:3306
【问题讨论】:
标签: python linux python-3.x ssh