简体   繁体   English

使用python通过ssh连接到mysql db

[英]Connecting to mysql db via ssh with python

I have tried solutions found on other SO questions but none of them have worked for me.我已经尝试过在其他 SO 问题上找到的解决方案,但没有一个对我有用。 I am attempting to pull data from a mysql db running on a remote server by setting up an ssh tunnel.我试图通过设置 ssh 隧道从远程服务器上运行的 mysql 数据库中提取数据。 My code is as follows:我的代码如下:

server = sshtunnel.SSHTunnelForwarder(
            ('10.6.41.10', 22),
            ssh_username= 'serveruser',
            ssh_password= 'serverpw',
            remote_bind_address=('127.0.0.1', 3306))

server.start()
print(server.local_bind_port)

cnx = mysql.connector.connect(user='root', password='mysqlpw',
                              host='127.0.0.1',
                              database='mydb',
                              charset='utf8',
                              use_unicode='FALSE',
                              port = 3306)

However, when I run this code I receive:但是,当我运行此代码时,我收到:

1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I have also tried adding我也试过添加

local_bind_address = ('0.0.0.0', 3306)

to the sshtunnel setup and instead recieved到 sshtunnel 设置,而是收到

Problem setting SSH Forwarder up: Couldn't open tunnel 0.0.0.0:3306 <> 127.0.0.1:3306 might be in use or destination not reachable

I don't fully understand the remote_bind_address and local_bind_address, so my guess is that must be doing something wrong there.我不完全理解 remote_bind_address 和 local_bind_address,所以我的猜测是那里一定做错了什么。 I know my username/pw/server info is correct, I am able to ssh into my server via terminal and then use我知道我的用户名/密码/服务器信息是正确的,我可以通过终端 ssh 进入我的服务器,然后使用

mysql -h 127.0.0.1 -u root -p

to successfully log into my mysql server.成功登录到我的 mysql 服务器。 So what do I need to fix to get it running in python?那么我需要修复什么才能让它在 python 中运行? Thanks.谢谢。

If you don't specify local_bind_address in sshtunnel.SSHTunnelForwarder , the local port is allocated randomly.如果在sshtunnel.SSHTunnelForwarder没有指定local_bind_address ,则本地端口是随机分配的。 In that case set port=server.local_bind_port in mysql.connector.connect() .在这种情况下,在mysql.connector.connect()设置port=server.local_bind_port

Instead, you can also set local_bind_address=('0.0.0.0', [some port which is not in use]) in sshtunnel.SSHTunnelForwarder .取而代之的是,还可以设置local_bind_address=('0.0.0.0', [some port which is not in use])sshtunnel.SSHTunnelForwarder The sshtunnel.HandlerSSHTunnelForwarderError ("Problem setting...") tells you that you can't use local_bind_address=('0.0.0.0', 3306) . sshtunnel.HandlerSSHTunnelForwarderError ("Problem setting...") 告诉您不能使用local_bind_address=('0.0.0.0', 3306)

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

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