MySQL 5.7 引入 authentication_string 替代 password 列,8.0 移除 PASSWORD() 函數、引入臨時密碼、強制密碼策略。本文匯總 4 種重置方案:skip-grant-tables、初始化臨時密碼、mysql_secure_installation、Docker 環境專用,並解決「修改後功能不全」的 FLUSH PRIVILEGES 與 ALTER USER 雙重驗證問題。
# 1. 停止服務
systemctl stop mysqld
# 2. 啟用跳過權限
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --skip-networking"
systemctl start mysqld
# 或手動: mysqld_safe --skip-grant-tables --skip-networking &
# 3. 免密登入
mysql -uroot
# 4. 修改密碼 (5.7+ 用 authentication_string)
UPDATE mysql.user SET authentication_string = PASSWORD('NewStrongPass123!')
WHERE User='root' AND Host='localhost';
FLUSH PRIVILEGES;
# 5. 關鍵步驟:重新載入授權表 (否則 ALTER USER 失效)
# 退出 mysql 客戶端,重啟正常模式
systemctl unset-environment MYSQLD_OPTS
systemctl restart mysqld
# 6. 正常登入並執行 ALTER USER (完成雙重驗證)
mysql -uroot -p'NewStrongPass123!'
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
FLUSH PRIVILEGES;
# 1. 獲取臨時密碼 grep 'temporary password' /var/log/mysqld.log # 輸出: temporary password for root@localhost: XyZ#Abc123 # 2. 登入修改 (需 --connect-expired-password) mysql -uroot -p'XyZ#Abc123' --connect-expired-password ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!'; FLUSH PRIVILEGES;
mysql_secure_installation # 流程: # 1. 輸入當前密碼 (或臨時密碼) # 2. 設置驗證插件? N (建議使用 caching_sha2_password 原生) # 3. 修改 Root 密碼? Y -> 輸入新密碼 # 4. 移除匿名用戶? Y # 5. 禁止 Root 遠程? Y # 6. 移除 test 庫? Y # 7. 重載權限? Y
# 運行中的容器 docker exec -it mysql_container mysql -uroot -p # 容器內執行 ALTER USER # 或環境變量重置 (需重建容器) docker run -d \ -e MYSQL_ROOT_PASSWORD=NewStrongPass123! \ -v mysql_data:/var/lib/mysql \ mysql:8.0 # 現有數據卷重置密碼 docker run --rm \ -v mysql_data:/var/lib/mysql \ mysql:8.0 \ mysqld --initialize-insecure --user=mysql # 然後正常啟動容器,Root 無密碼,進入後 ALTER USER
| 項目 | 5.6 | 5.7 | 8.0 |
|---|---|---|---|
| 密碼列 | password | authentication_string | authentication_string |
| PASSWORD() 函數 | 支援 | 支援 (棄用) | **移除** |
| 默認認證插件 | mysql_native_password | mysql_native_password | caching_sha2_password |
| 密碼策略 | 無 | validate_password (可選) | 內建 validate_password |
| 臨時密碼 | 無 | 有 (初始化生成) | 有 |
ERROR 1820 (HY000): You must SET PASSWORD before executing this statementpassword_expired=Y。解決:執行 SET PASSWORD = 'newpass' 或 ALTER USER ... IDENTIFIED BY 'newpass'ERROR 1396 (HY000): Operation ALTER USER failed for 'root'@'localhost'SELECT User, Host FROM mysql.user WHERE User='root'; 確認 Host 值ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'pass'; (兼容舊驅動)FLUSH PRIVILEGES 後仍無效skip-grant-tables 模式下授權表不生效。解決:必須退出該模式重啟正常服務audit_log 記錄所有密碼修改操作