Search code examples
pythonmysqldatabase-connectionmysql-connector-pythonmysql-error-1130

Can't connect to localhost using mysql-connector-python, error 1130


I'm trying to connect to a local mysql database from pyhton using the mysql-connector-python. The mysql server is set up to allow only local connections. It works with many other applications, but not in my python script. I'm using the following:

db_config = {'host': 'localhost', 'user': 'aaa', 'password': 'xxx', 'database': 'aaa'}
conn = mysql.connector.connect(**db_config)

and I get the following error:

mysql.connector.errors.DatabaseError: 1130: Host 'static-xxx-xxx-xxx-xxx.net.upcbroadband.cz' is not allowed to connect to this MySQL server

where static-xxx-xxx-xxx-xxx.net.upcbroadband.cz is a hostname corresponding to my public static ip address.

I tried changing the host parameter to 127.0.0.1, but it didn't help.

Interestingly, when I try to login from the terminal: mysql -h localhost -u aaa -p, there is no problem, however, when I do: mysql -h 127.0.0.1 -u aaa -p, I get the same error,

ERROR 1130 (HY000): Host 'static-xxx-xxx-xxx-xxx.net.upcbroadband.cz' is not allowed to connect to this MySQL server

Is it possible, that mysql-connector-python somehow converts the localhost to public ip?


Solution

  • Turns out, MASQUERADE was set up for all external packets:

    sudo iptables --table nat --list
    
    [...]
    Chain POSTROUTING (policy ACCEPT)
    target     prot opt source               destination
    MASQUERADE  all  --  10.0.0.0/8           anywhere
    MASQUERADE  all  --  anywhere             anywhere
    

    When I removed it by sudo iptables -t nat -D POSTROUTING -j MASQUERADE the problem was solved.

    I actually figured this out when trying

    mysql -h localhost --protocol=TCP
    

    which again produced the 1130 error resolving localhost to public hostname. That means, if I understand it correctly, that mysql-connector-python is using TCP by default contrary to the mysql command.