2016-09-18 220 views
2

我需要一些幫助,使用Python腳本在桌面PC上將表從桌面PC添加到現有MySQL數據庫(db名稱DB2639162)。我寫了下面的腳本(create_db.py):使用Python連接到MySQL通過SSH

import MySQLdb 
from sshtunnel import SSHTunnelForwarder 
ssh_pwd='' 
ssh_usr='' 
mysql_pwd='' 
mysql_usr='' 
with SSHTunnelForwarder(('ssh.strato.de', 22), 
         ssh_password=ssh_pwd, ssh_username=ssh_usr, 
         remote_bind_address=('rdbms', 3306)) as server: 
    print 'Server connected via SSH!' 

    db1 = MySQLdb.connect(host='127.0.0.1', 
         port=server.local_bind_port, 
         user=mysql_usr, 
         passwd=mysql_pwd, 
         db='DB2639162') 
    cursor = db1.cursor() 
    sql = 'CREATE TABLE mydata' 
    cursor.execute(sql) 
    db1.close() 

但不幸的是腳本不起作用,我得到下面的輸出。顯然,SSH連接可以成功建立,但對數據庫的訪問失敗。

Server connected via SSH! 
2016-09-18 11:02:19,291| ERROR | Secsh channel 0 open FAILED: open failed: Administratively prohibited 
2016-09-18 11:02:19,295| ERROR | Could not establish connection from ('127.0.0.1', 44017) to remote side of the tunnel 
Traceback (most recent call last): 
    File "create_db.py", line 18, in <module> 
    db='DB2639162') 
    File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 81, in Connect 
    File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 193, in __init__ 
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") 

此外,用戶名,密碼都很好,因爲終端命令工作正常,並授予我訪問MySQL數據庫的權限。

ssh [email protected] 
mysql -h rdbms -u mysql_usr -p DB2639162 

預先感謝您

+0

你是否設法解決這個問題? –

回答

1

答案是正確的,在錯誤消息:

2016年9月18日11:02:19291 |錯誤| Secsh通道0打開失敗:打開失敗:管理禁止

在服務器上的shell會話中運行MySQL命令行客戶端並設置端口轉發/隧道是完全不同的事情。你可以做到這一點並不意味着你可以做另一個。

該服務器顯然禁止端口轉發/隧道(「Administratively prohibited」)。你需要一個不同的方法。

+0

你提到使用不同的方法,你能爲此提出一些建議嗎? –