pythonmysqlmariadbssh-tunnelmysql-connector-python

python sshtunnel not starting server given credentials


So I'm trying to get mysql-connector-python to work with sshtunnel

with SSHTunnelForwarder(('192.168.0.1', 22), ssh_username='pi', ssh_password='*********', remote_bind_address=('localhost', 3306)) as tunnel:
    tunnel.start()
    mydb = mysql.connector.connect(host="localhost",
                                   user='Mashu',
                                   password='*******',
                                   port=tunnel.local_bind_port,
                                   db='mysql')

print(mydb)
cur = mydb.cursor()
cur.execute('USE mysql')
print(cur.execute('SELECT * FROM user'))

And it seems to execute smoothly, but when I want to create cursor it says

mysql.connector.errors.OperationalError: MySQL Connection not available.

I investigated it further and found out that values connected to local binding, so local_bind_address, local_bind_host, etc. are all set to errors, saying:

Server is not started. Please .start() first!

Even though I do have tunnel.start() in my code
I did check, and my server is visible for other programs (f.e. DataGrip), I have no idea where the problem is.


Solution

  • You're using a context manager with with SSHTunnelForwarder, meaning that it will close the connection when it exits the scope. Putting the cur = mydb.cursor inside the context manager scope will solve the issue.