啟動 MySQL 時跳過權限表 (skip-grant-tables),以空密碼 root 登入,更新 mysql.user 表的 authentication_string (5.7+) 或 Password (5.6-) 欄位,重啟恢復正常驗證。
# 1. 確保安全:關閉對外端口、停止應用、最佳在主控台操作
# 2. 編輯配置
vi /etc/my.cnf
# [mysqld] 段下添加
skip-grant-tables
# 3. 重啟
systemctl restart mysqld # 或 service mysqld restart
# 4. 免密登入並改密
mysql -u root
UPDATE mysql.user SET authentication_string=PASSWORD('NewPwd123!') WHERE User='root';
FLUSH PRIVILEGES;
EXIT;
# 5. 移除 skip-grant-tables 並重啟
vi /etc/my.cnf # 刪除該行
systemctl restart mysqld
# 6. 驗證新密碼
mysql -u root -p'NewPwd123!'
# 1. 停止服務
systemctl stop mysqld
# 2. 後台啟動跳過權限
mysqld_safe --skip-grant-tables &
# 3. 免密登入改密 (同方案一步驟 4)
# 4. 正常重啟
systemctl restart mysqld
systemctl stop mysql
mysqld --skip-grant-tables &
mysql -u root
UPDATE mysql.user SET authentication_string=PASSWORD('NewPwd123!') WHERE User='root';
FLUSH PRIVILEGES;
EXIT;
systemctl restart mysql
authentication_string (長文本),Password 欄位廢棄。PASSWORD() 函數在 8.0 移除,建議用 ALTER USER 'root'@'localhost' IDENTIFIED BY 'pwd'; (需正常驗證模式下)。FLUSH PRIVILEGES; 必須執行,否則修改不生效。skip-grant-tables 期間資料庫完全無保護,任何人可無密登入並任意增刪改查。務必:
1. 防火牆封鎖 3306 對外。
2. 停止所有應用服務。
3. 操作完成 立即 移除參數並重啟。
# 一鍵驗證新密碼
mysql -uroot -p'NewPwd123!' -e "SELECT USER(), CURRENT_USER();"
三種方案覆蓋主流 Linux 發行版,收藏備用,關鍵時刻救命。