A way to disable SSL using python MySQLdb connector

Viewed 7847

Opening a connection using SSL with python connector gives me following error:

MySQLdb.connect(host='host',user='user,passwd='xxx',db='xxx',)

OperationalError: (2026, 'SSL connection error: ASN: unknown key OID type')

The same is when I am using bash mysql command:

mysql -p -u user -h host
Enter password:
ERROR 2026 (HY000): SSL connection error: ASN: unknown key OID type

The only way around I have found was to use --ssl-mode=DISABLED

mysql -p -u user -h host --ssl-mode=DISABLED
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.

Is there any way I am able to mimic this using python connector? I am using mysql v 5.7.26 on Ubuntu 16.04 and python 3.5.2.

4 Answers

Connect to mysql/mariaDB without SSL in python:

import mysql.connector
from mysql.connector import Error

mysql_config = {
        'user': 'DB-user',
        'password': 'userpassword',
        'host': 'localhost',
        'database': 'your-DB-name',
        'port': '3306',
        'ssl_disabled': True
    }

try:
    cnx = mysql.connector.connect(**mysql_config)
    if cnx.is_connected():
        print('connected to database') 

except Error as e:
    print("mysql DB connection error")
    print(e)

Also see full documentation: Mysql Connector/Python Connection Arguments.

If you want to connect via mysqlx, see examples on Getting started with mysqlx.

As the original poster mentioned in his comment, one of the most convenient ways to disable SSL in Python — is by using pip install mysql-connector-python and then employing the ssl_disabled key.

mysql.connect(host=HOST, database=DATABASE, port=PORT, user=USER, password=PASSWORD, ssl_disabled=True/False)

So the code would look like this:

    import mysql.connector as mysql
    
    db_connection = mysql.connect(host=HOST, database=DATABASE, port=PORT, user=USER, password=PASSWORD, ssl_disabled=True)
    print("Connected to:", db_connection.get_server_info())
    db_handler = connection.cursor()
    db_handler.execute("SELECT * from your_table")
    fetch_result = db_handler.fetchall()
    for item in fetch_result:
        print(item)

According to manual, "ssl" key manages, if present, the ssl protocol. So I supose passing a void dictionary on this tag, may work for you. (Works in may Try this:

mysql_config = {
        'user': 'DB-user',
        'password': 'userpassword',
        'host': 'localhost',
        'database': 'your-DB-name',
        'port': '3306',
        'ssl': {}
    }
self.connection = MySQLdb.connect(**mysql_config )
self.connection.autocommit(True)
return database.DBOK

Note that mysqlclient also supports the ssl_mode param since version 2.0.0. With that you can also do:

MySQLdb.connect(host='host', user='user', passwd='xxx', db='xxx', ssl_mode='DISABLED')

Related