Python MySQL连接器不适用于SSL

时间:2019-03-18 12:57:14

标签: python mysql python-2.7 mysql-python

我最近在MySQL服务器上配置了SSL,它似乎损坏了我的python应用程序。我可以通过命令行连接到服务器。

user@kiosk:~$ mysql -u <user> -p -h <remote host>
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

并且SSL似乎正在建立连接:

mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.7.25, for Linux (x86_64) using  EditLine wrapper

Connection id:          19
Current database:
...
SSL:                    Cipher in use is DHE-RSA-AES256-SHA
....

Threads: 1  Questions: 17  Slow queries: 0  Opens: 106  Flush tables: 1  Open tables: 99  Queries per second avg: 0.007

该用户配置为需要SSL,并且我目前未在客户端上使用CA / client-cert / client-key进行连接(据我了解,这是可选的)。

我的python脚本使用一个简单的连接:

db_ip_address = raw_input('Ip Address: ')
db_username = raw_input('Username: ')
db_passwd = raw_input('Password: ')

try:
    db = mysql.connector.connect(
         host=db_ip_address,
         user=db_username,
         passwd=db_passwd,
    )
    cursor = db.cursor()
    connected = True

except Exception as e:
    installer.fatal('\r\n Failed to connect to SQL server please try again \r\n')
    print traceback.format_exception_only(type(e), e)[0]

现在失败,并出现以下错误:

ProgrammingError: 1045 (28000): Access denied for user '<user>'@'<IP>' (using password: YES)

我认为这是由于我的SSL配置引起的,但是我不确定是为什么从mysql CLI可以正常运行,但不能从脚本正常运行吗?

任何见识将不胜感激。

1 个答案:

答案 0 :(得分:1)

以下错误是关于错误的登录信息,例如您的用户名或密码或IP地址。 如果您的用户名和密码正确,请检查数据库中允许的IP(%或localhost或127.0.0.1)。 对于ssl连接,请检查以下代码:

import sys

#sys.path.insert(0, 'python{0}/'.format(sys.version_info[0]))

import mysql.connector
from mysql.connector.constants import ClientFlag

config = {
    'user': 'ssluser',
    'password': 'password',
    'host': '127.0.0.1',
    'client_flags': [ClientFlag.SSL],
    'ssl_ca': '/opt/mysql/ssl/ca.pem',
    'ssl_cert': '/opt/mysql/ssl/client-cert.pem',
    'ssl_key': '/opt/mysql/ssl/client-key.pem',
}

cnx = mysql.connector.connect(**config)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()

来自here

here如何使用ssl设置mysql