Connecting to mysql db via ssh with python

时间:2017-10-24 14:42:33

标签: python mysql ssh

I have tried solutions found on other SO questions but none of them have worked for me. I am attempting to pull data from a mysql db running on a remote server by setting up an ssh tunnel. 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

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. I know my username/pw/server info is correct, I am able to ssh into my server via terminal and then use

mysql -h 127.0.0.1 -u root -p

to successfully log into my mysql server. So what do I need to fix to get it running in python? Thanks.

1 个答案:

答案 0 :(得分:1)

如果您未在local_bind_address中指定sshtunnel.SSHTunnelForwarder,则会随机分配本地端口。在这种情况下,在port=server.local_bind_port中设置mysql.connector.connect()

相反,您也可以在local_bind_address=('0.0.0.0', [some port which is not in use])中设置sshtunnel.SSHTunnelForwardersshtunnel.HandlerSSHTunnelForwarderError(&#34;问题设置...&#34;)告诉您,您无法使用local_bind_address=('0.0.0.0', 3306)

相关问题