生產環境誤忘 MySQL root 密碼是運維高發場景。本文提供標準化、可落地的 skip-grant-tables 繞過認證重置流程,並強調安全收尾步驟,防止長期裸奔風險。
在 [mysqld] 節點添加 skip-grant-tables 後重啟,MySQL 啟動時不加載權限表,所有連接無需密碼即可獲得最高權限,從而直接操作 mysql.user 表修改密碼。
# Linux: /etc/my.cnf 或 /etc/mysql/my.cnf
# Windows: my.ini(通常在安裝目錄或 C:\ProgramData\MySQL\MySQL Server x.x\)
[mysqld]
port=3306
skip-grant-tables # 新增此行,建議置於 port 之後
# Linux systemd
systemctl restart mysqld
# Windows 管理員 CMD / PowerShell
net stop mysql
net start mysql
mysql -u root
# 進入後直接回車,無需輸入密碼
# MySQL 5.7+ (authentication_string 列)
UPDATE mysql.user SET authentication_string = PASSWORD('NewStrongPass123!') WHERE User = 'root';
# MySQL 5.6 或更早 (password 列)
UPDATE mysql.user SET password = PASSWORD('NewStrongPass123!') WHERE User = 'root';
FLUSH PRIVILEGES;
EXIT;
# 註釋或刪除該行
# skip-grant-tables
systemctl restart mysqld # 或 net stop/start mysql
mysql -u root -p'NewStrongPass123!' -e "SELECT VERSION();"
bind-address=127.0.0.1 限制本地訪問--init-file 方式重置,更安全無需重啟兩次# 1. 創建初始化文件 /tmp/init.sql
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
# 2. 啟動時指定
mysqld --init-file=/tmp/init.sql --user=mysql
# 3. 登錄驗證後刪除 init 文件
建議將此流程納入運維應急預案,定期演練,關鍵時刻不手忙腳亂。