Python:mysql.connector 和 SSL 出错,但适用于 pymysql.connect

Python: Error with mysql.connector and SSL, but works with pymysql.connect

对于一个项目,我需要更改现有代码以支持使用 SSL 证书的 MySQL 连接。实现的包是 mysql.connector 并且大量集成在源代码的其他部分,所以用 pymysql 替换它不是一个选项。

使用以下配置:

config = {
    'user': 'ssl-username',
    'password': 'password',
    'host': '4.1.3.2',
    'ssl_ca': '/path/to/ca.pem',
    'ssl_cert': '/path/to/cert.pem',
    'ssl_key': '/path/to/key.pem'
}

以下尝试失败:

mysql.connector.connect(**config, client_flags=[ClientFlag.SSL])
mysql.connector.connect(**config, client_flags=[ClientFlag.SSL], use_pure=True)

以下作品:

pymysql.connect(**config)

失败尝试的痕迹提供了以下信息:

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/network.py", line 421, in switch_to_ssl
    self.sock.do_handshake()
  File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL] internal error (_ssl.c:1123)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/connection.py", line 95, in __init__
    self.connect(**kwargs)
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/abstracts.py", line 716, in connect
    self._open_connection()
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/connection.py", line 208, in _open_connection
    self._do_auth(self._user, self._password,
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/connection.py", line 134, in _do_auth
    self._socket.switch_to_ssl(**ssl_options)
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/network.py", line 426, in switch_to_ssl
    raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2055: Lost connection to MySQL server at '34.91.73.12:3306', system error: 1 [SSL] internal error (_ssl.c:1123)
>>> del conn_args["client_flags"]
>>> mysql.connector.connect(**conn_args)
Traceback (most recent call last):
  File "/home/user/.local/lib/python3.8/site-packages/mysql/connector/network.py", line 421, in switch_to_ssl
    self.sock.do_handshake()
  File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL] internal error (_ssl.c:1123)

可能出了什么问题,因为错误消息的描述性不强。

我让它休息了一会儿,经过新的调查,我找到了罪魁祸首。显然该软件包已从 mysql-connector 重命名为 mysql-connector-python。由于错误本身不完整,因此需要手动检查代码才能确定 pip3 的最新版本实际上不是最新版本。