Root 密碼遺忘是資料庫運維高頻事故。核心原理:以 --skip-grant-tables 參數啟動 MySQL,暫時繞過權限驗證,直接更新 mysql.user 表修改密碼雜湊值。本文提供 Linux 與 Windows 完整操作步驟、常見坑點與驗證清單。
正常啟動:mysqld → 載入 grant tables → 驗證密碼 → 允許/拒絕連線 緊急模式:mysld --skip-grant-tables → 不載入 grant tables → 無密碼直連 → 直接 UPDATE user 表 → FLUSH PRIVILEGES → 正常重啟
systemctl stop mysqld # 或 service mysqld stop # 確認進程已終結 ps aux | grep mysqld
# 前台運行(方便觀察日誌),另開終端機操作 mysqld_safe --skip-grant-tables --skip-networking &
--skip-networking 僅允許本地 Unix Socket 連線,提升安全性。
mysql -u root
# 進入 mysql> 提示符後執行:
USE mysql;
-- MySQL 5.7.6+ 欄位名為 authentication_string
UPDATE user SET authentication_string=PASSWORD('NewStrongPass2024!') WHERE User='root' AND Host='localhost';
-- MySQL 5.7.6 前欄位名為 password
-- UPDATE user SET password=PASSWORD('NewStrongPass2024!') WHERE User='root' AND Host='localhost';
FLUSH PRIVILEGES;
EXIT;# 終止 --skip-grant-tables 進程 pkill -f "mysqld_safe --skip-grant-tables" # 正常啟動 systemctl start mysqld # 驗證新密碼 mysql -u root -p'NewStrongPass2024!' -e "SELECT 'Login Success';"
net stop mysql 或 sc stop mysqlbin 目錄啟動跳過授權模式:
cd "C:\Program Files\MySQL\MySQL Server 5.7\bin" mysqld --skip-grant-tables --skip-networking
mysql -u rootnet start mysql| 坑點 | 現象 | 解決方案 |
|---|---|---|
| SET PASSWORD 失敗 | ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement | 必須使用 UPDATE 直接修改 user 表,不可用 SET PASSWORD |
| plugin 欄位為 caching_sha2_password | 新密碼無法驗證 | 同時更新 plugin='mysql_native_password' 或使用 ALTER USER (需重啟後) |
| 多個 root 帳號 (localhost, 127.0.0.1, ::1, %) | 部分主機仍無法登入 | WHERE 條件包含所有 Host,或統一用 %(不建議生產環境) |
| Windows 服務名稱非預設 | net stop mysql 失敗 | 用 sc query type= service state= all | findstr -i mysql 確認服務名 |
| AppArmor/SELinux 阻擋 mysqld 讀寫 datadir | 跳過授權模式啟動失敗 | 臨時設定 permissive 模式或調整策略 |