简体   繁体   English

使用 Python 通过 SSH 连接到 MySQL

[英]Connecting to MySQL over SSH using Python

I need some help adding tables from a desktop PC to an existing MySQL database (db name DB2639162) on a webserver using a python script.我需要一些帮助,使用 python 脚本将台式 PC 中的表添加到 Web 服务器上的现有 MySQL 数据库(数据库名称 DB2639162)。 I have written the following script (create_db.py):我编写了以下脚本(create_db.py):

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

But unfortunately the script does not work and I get the output below.但不幸的是脚本不起作用,我得到了下面的输出。 Obviously, the SSH connection can be established successfully, but the access to the database fails.显然可以成功建立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")

Additionally, the usernames, passwords are fine as the terminal commands work well and grant me access to the MySQL database.此外,用户名、密码都很好,因为终端命令运行良好并授予我访问 MySQL 数据库的权限。

ssh ssh_usr@ssh.strato.de
mysql -h rdbms -u mysql_usr -p DB2639162

Thank you in advance先感谢您

The answer is right there in the error message:答案就在错误消息中:

2016-09-18 11:02:19,291| 2016-09-18 11:02:19,291| ERROR |错误 | Secsh channel 0 open FAILED: open failed: Administratively prohibited Secsh 通道 0 打开失败:打开失败:管理禁止

Running the MySQL command-line client in a shell session on a server and setting up port forwarding/tunneling are completely different things.在服务器上的 shell 会话中运行 MySQL 命令行客户端和设置端口转发/隧道是完全不同的事情。 The fact that you can do one does not imply that you can do the other.你可以做一个的事实并不意味着你可以做另一个。

This server obviously forbids port forwarding/tunneling ("Administratively prohibited").该服务器显然禁止端口转发/隧道(“管理禁止”)。 You'll need a different approach.你需要一种不同的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM