我需要一些帮助,使用 Python 脚本将桌面 PC 中的表添加到网络服务器上的现有 MySQL 数据库(数据库名称 DB2639162)。我编写了以下脚本 (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()
但不幸的是,脚本无法运行,我得到以下输出。很明显,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 ssh_usr@ssh.strato.de
mysql -h rdbms -u mysql_usr -p DB2639162
提前致谢
最佳答案
答案就在错误信息中:
2016-09-18 11:02:19,291| ERROR | Secsh channel 0 open FAILED: open failed: Administratively prohibited
在服务器的 shell session 中运行 MySQL 命令行客户端和设置端口转发/隧道是完全不同的事情。事实上,您可以做一个并不意味着您可以做另一个。
此服务器显然禁止端口转发/隧道(“管理禁止”)。您需要一种不同的方法。
关于python - 使用 Python 通过 SSH 连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556553/