2

I'm connecting to MySQL db through SSH on server. I managed to do it through MySql workbench and through system shell, which means passwords, username and ip are correct and allowed.

Now I'm trying to connect through Python. I'm using sshtunnel package with the same settings as in workbench (in shell all was default) - mysql port 3306, ssh port 22, mysql hostname 127.0.0.1 and it connects me. When I'm trying to connect through connector to db I'm getting:

mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'myusername'@'localhost' (using password: YES).

I also tried to connect directly through shell with python using: os.system("mysql -u myusername -p") and I got:

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

I checked here:

Can't access MySQL through MySQL Workbench or HeidiSQL, but can access through shell

Accessing MySQL from Python 3: Access denied for user

And many more, but I found nothing helpful. My Python version is 3.6.8, MySql version is 5.7.31. What other thing may differ between shell accessed by python and the normal Unix one? Or access got by workbench?

Edit:

Requested code. All of the three connections gave exactly the same output.

with sshtunnel.SSHTunnelForwarder(
        (ssh_host, ssh_port),
        ssh_username=ssh_username,
        ssh_password=ssh_password,
        remote_bind_address=('localhost', mysql_port)) as tunnel:
    

    # conn = mysql.connector.connect(**mysql_config)
    conn = MySQLdb.connect(host="localhost", 
    user="myusername", passwd="password", db="mydb")
    print(conn)
    # print(os.system("mysql -u myusername -p"))
Manaslu
  • 228
  • 1
  • 13
  • please show your sanitizes code, also check https://stackoverflow.com/questions/21903411/enable-python-to-connect-to-mysql-via-ssh-tunnelling – nbk Sep 07 '20 at 09:37
  • Code added. That link was my first google outcome, but it doesn't address the problem. – Manaslu Sep 07 '20 at 09:49

1 Answers1

2

I managed to connect with:

tunnel = sshtunnel.SSHTunnelForwarder((ssh_host, 22), ssh_password=ssh_password, ssh_username=ssh_username,
     remote_bind_address=('localhost', 3306))
tunnel.start()

Apparently the difference was to keep the tunnel open instead of using 'with' statement, though I don't understand what actually happened and I'd appreciate explanation.

Manaslu
  • 228
  • 1
  • 13