遺忘 MySQL root 密碼是經典運維場景。本文提供兩種 --skip-grant-tables 啟動模式(命令列臨時啟動 / 修改 my.cnf 永久生效),完整步驟含停服務、跳過授權表、免密登入、更新密碼、刷新權限、恢復正常啟動,並強調網路隔離與權限收尾細節。
# 1. 停止服務
service mysqld stop
# 或 killall mysqld
# 2. 跳過授權表啟動(建議加 --skip-networking 禁用網路)
/usr/local/mysql/bin/mysqld_safe --skip-grant-tables --skip-networking &
# 3. 免密登入
mysql -u root -p # 提示密碼直接 Enter
# 4. 更新密碼
USE mysql;
UPDATE user SET Password = PASSWORD('newpass') WHERE User = 'root';
FLUSH PRIVILEGES;
QUIT;
# 5. 結束臨時進程
killall mysqld
# 6. 正常啟動
service mysqld start
# 7. 新密碼驗證
mysql -u root -p'newpass'
# 1. 編輯配置
vi /etc/my.cnf
[mysqld]
skip-grant-tables
# 2. 重啟服務
service mysqld restart
# 3. 免密登入並更新密碼(同方法一步驟 3-4)
# 4. 移除 skip-grant-tables 並重啟
vi /etc/my.cnf # 刪除該行
service mysqld restart
user 表後必須執行,否則新密碼不生效。user 表欄位改為 authentication_string,更新語句:UPDATE user SET authentication_string = PASSWORD('newpass') WHERE User = 'root';caching_sha2_password 插件,舊客戶端可能需 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpass';按流程操作,root 密碼重置通常 5 分鐘內完成,關鍵在於「跳過授權 → 改密 → 刷新 → 恢復正常」四步不漏。