You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用mysql-connector-python连接远程MySQL遇2013错误求助

解决远程MySQL连接报错:2013 (HY000) Lost connection to MySQL server at 'reading initial communication packet'

剩余排查方案

1. 检查MySQL用户的远程访问权限

你创建的用户可能仅允许本地访问(如user@localhost),需确保用户权限支持远程IP访问:

  • 登录MySQL服务器执行:
    SELECT user, host FROM mysql.user WHERE user = '<你的用户名>';
    
  • 如果返回的host不是%(允许所有IP)或你的客户端IP,更新权限:
    GRANT ALL PRIVILEGES ON <你的数据库名>.* TO '<你的用户名>'@'%' IDENTIFIED BY '<你的密码>';
    FLUSH PRIVILEGES;
    
    (注:%为通配所有IP,也可指定具体客户端IP提升安全性)

2. 调整max_allowed_packet配置

该参数过小会导致初始通信包传输失败,修改my.cnf(或my.ini)的[mysqld]段:

max_allowed_packet = 64M

修改后重启MySQL服务。

3. 强制使用纯Python协议连接

若telnet能连通但Python报错,在连接配置中添加use_pure=True:

config = {
  'user': '<user>',
  'password': '<password>',
  'host': '<IP>',
  'port': <port>,
  'database': '<database>',
  'use_pure': True
}

此参数会绕过C扩展协议,避免兼容性问题。

4. 查看MySQL错误日志

检查MySQL错误日志(通常路径为/var/log/mysql/error.log),日志中会记录连接失败的具体原因,如权限拦截、配置冲突等。

5. 确认MySQL实际监听端口

尽管nmap显示3306开放,仍需确认MySQL实际监听端口与配置一致:

netstat -tulpn | grep mysql

对比输出的端口号与代码中<port>参数是否匹配。


附你的测试代码:

import mysql.connector
from mysql.connector import errorcode

config = {
  'user': '<user>',
  'password': '<password>',
  'host': '<IP>',
  'port': <port>,
  'database': '<database>'
}

try:
    cnx = mysql.connector.connect(**config)
    cursor = cnx.cursor()

    query = ('SELECT * FROM student')
    print(f'Executing Query: {query}')

    cursor.execute(query)

    for id, name in cursor:
        print(f'ID: {id}, Name: {name}')

except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('用户名或密码错误')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('数据库不存在')
    else:
        print(err)
else:
    cursor.close()
    cnx.close()

内容的提问来源于stack exchange,提问作者YTKme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 04:01:17