无法使用 PyMySQL 与远程 MySQL 服务器建立 TLS TCP 连接,其他工具可以工作

Unable to make TLS TCP connection to remote MySQL server with PyMySQL, other tools work

设置一个我想与中央 MySQL 数据库通信的新服务器,使用 TLS 连接确保安全

按照 this 这样的步骤,我已经能够为我的 MySQL 服务器设置 TLS,我已经让几个用户能够从任何主机登录 (%),并且需要 SSL连接

+------------+-----------+----------+
| user       | host      | ssl_type |
+------------+-----------+----------+
| testuser   | %         | ANY      |
+------------+-----------+----------+

我可以在任何主机上通过使用 HeidiSQL 或 MySQL CLI 工具等工具进行连接来确认这一点 例如:mysql -u testuser -p -h mysql_server_IP 这将启动一个 TLS 连接,由 \s 确认 这排除了我在这个和其他论坛上看到的大多数问题,这些问题是由主机设置为本地主机引起的。

当访问本地数据库时,以下操作正常。当连接到非 TLS 远程数据库服务器时,它也可以正常工作。

import pymysql.cursors

connection = pymysql.connect(host=host,
                             user=user,
                             password=password,
                             db=db,
                             cursorclass=pymysql.cursors.DictCursor)

尝试使用 require-tls 访问我的服务器时,我收到以下错误 pymysql.err.OperationalError: (1045, "Access denied for user 'testuser'@'desktop.example.com' (using password: YES)")

我的其他发现表明该错误是由以下原因引起的: 无效的用户名/密码组合,或者该主机禁止的连接。但是我知道我可以从该主机建立连接,如 CLI 所示。

当连接到在 my.cnf 中只有 require_secure_transport = ON 的服务器时,PyMySQL 给出了一个更明显的无法启动 TLS 连接的错误。 pymysql.err.InternalError: (3159, 'Connections using insecure transport are prohibited while --require_secure_transport=ON.' 但是如果 MySQL 用户本身需要 SSL,您会从上面的问题中得到更通用的权限被拒绝错误。

github issue tracker there is mention of supplying the CA .pem file. If you don't have access to these files and want to trust the self signed cert implicitly. The docs 中提及 -ssl 标志,它允许您为各种证书文件传递路径。

但是,通过传入有效字典,无需任何有效密钥,您可以有效地全面信任自签名证书。示例:

connection = pymysql.connect(host=host,
                             user=user,
                             password=password,
                             db=db,
                             cursorclass=pymysql.cursors.DictCursor,
                             ssl={"fake_flag_to_enable_tls":True})