2016-09-22 82 views
0

我通過SSH連接到遠程SQL數據庫。如果我從Linux命令行設置SSH連接(使用ssh-add my_private_key.key,然後使用ssh [email protected]),則連接時間不到一秒鐘。但是如果我使用sshtunnel(在下面的腳本中)使用Python來完成,大約需要70秒。我接受使用Python可能會帶來一些開銷,但不是那麼多!特別是因爲如果我在從命令行連接後運行Python腳本,速度非常快。我需要在腳本中添加哪些內容以使其更快?來自Python的SSH隧道連接太慢

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 

回答

0

衛生署!在發佈這個問題之後,我認爲確保sshtunnel是最新版本是一個不錯的主意 - 事實並非如此。所以我已經從0.0.8.1更新到最新版本(0.1.0),我的問題解決了!