重置期間 MySQL **完全無密碼保護**,任何人可任意登錄修改。必須:
vi /etc/my.cnf
# 在 [mysqld] 區段添加
skip-grant-tables
示例:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
skip-grant-tables
/etc/init.d/mysqld restart
# 或
service mysqld restart
# systemd 系統
systemctl restart mysqld
/usr/bin/mysql
# 進入 mysql> 提示符後
USE mysql;
UPDATE user SET Password = PASSWORD('new-password') WHERE User = 'root';
FLUSH PRIVILEGES;
QUIT;
注意: MySQL 5.7+ user 表無 Password 列,改為 authentication_string:
UPDATE user SET authentication_string = PASSWORD('new-password') WHERE User = 'root';
FLUSH PRIVILEGES;
MySQL 8.0+ 推薦:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password';
FLUSH PRIVILEGES;
vi /etc/my.cnf
# 刪除 skip-grant-tables 行
/etc/init.d/mysqld restart
mysql -u root -p'new-password' -e "SELECT VERSION();"
| 現象 | 原因 | 解決 |
|---|---|---|
| UPDATE 影響 0 行 | Host 不匹配(如 'root'@'127.0.0.1') | WHERE User='root' AND Host='%' 或逐個 Host 更新 |
| 密碼生效但應用連不上 | 應用配置未同步修改 | 更新應用端連接字符串 |
| skip-grant-tables 無效 | 配置文件區段錯誤/未重啟 | 確認在 [mysqld] 區段、已重啟服務 |
若可短暫停機,可用 --init-file 方式:
# 1. 創建 init.sql
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password';
# 2. 啟動時加載
mysqld --init-file=/path/to/init.sql --user=mysql
# 3. 登錄驗證後移除 --init-file 參數正常啟動
此法無需 skip-grant-tables,安全性更高。