MySQL root 密碼遺忘或密碼過期導致無法登入,是運維高頻場景。本文提供 Windows/Linux 通用的 skip-grant-tables 繞過驗證流程,並針對 MySQL 5.7+ password 字段重命名為 authentication_string 的變更給出正確修改語句。
my.ini / my.cnf),[mysqld] 下添加 skip-grant-tablesmysql -u root (無需 -p)USE mysql;
-- MySQL 5.7.6+ (含 5.7.13、8.0 前)
UPDATE user SET authentication_string=PASSWORD('newpass') WHERE user='root';
-- MySQL 5.7.6 之前 / 5.6
UPDATE user SET password=PASSWORD('newpass') WHERE user='root';
FLUSH PRIVILEGES;
skip-grant-tables登入後提示:ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
mysql.user 表:UPDATE user SET password_expired='N' WHERE user='root';
FLUSH PRIVILEGES;
skip-grant-tables,重啟服務| 版本 | 密碼字段 | 修改語句 | 密碼過期字段 |
|---|---|---|---|
| 5.6 / 5.7.0-5.7.5 | password | SET password=PASSWORD('x') | password_expired |
| 5.7.6+ | authentication_string | SET authentication_string=PASSWORD('x') | password_expired |
| 8.0+ | authentication_string | ALTER USER ... IDENTIFIED BY 'x' | password_expired (已棄用,改用 password_last_changed) |
skip-grant-tables 期間繞過所有權限檢查,任何網路連接均可無密訪問bind-address=127.0.0.1-- 修改密碼 (推薦)
ALTER USER 'root'@'%' IDENTIFIED BY 'newpass';
-- 設置密碼過期策略
ALTER USER 'root'@'%' PASSWORD EXPIRE INTERVAL 90 DAY;
-- 解鎖帳號
ALTER USER 'root'@'%' ACCOUNT UNLOCK;
建議建立密碼管理 SOP:定期輪換、密碼複雜度策略、避免硬編碼配置文件、使用 Vault 等密碼管理系統。