萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 修改與重設 root 密碼完整教學(含忘記密碼救援)

情境一:已知密碼,正常修改

方法 1:SET PASSWORD 指令

mysql -u root -p
# 登入後
SET PASSWORD = PASSWORD('new_strong_pass');
FLUSH PRIVILEGES;

方法 2:GRANT 重新授權(同時可設定主機)

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'new_strong_pass' WITH GRANT OPTION;
FLUSH PRIVILEGES;

方法 3:直接更新 user 表

USE mysql;
UPDATE user SET Password = PASSWORD('new_strong_pass') WHERE User = 'root';
FLUSH PRIVILEGES;

情境二:忘記 root 密碼(跳過授權表啟動)

步驟概覽

  1. 停止 MySQL 服務
  2. 以 --skip-grant-tables 參數啟動
  3. 免密登入並更新密碼
  4. 正常重啟服務

Linux 環境詳細操作

# 1. 停止服務
systemctl stop mysqld

# 2. 建立臨時啟動腳本或直接加參數啟動
# 方法 A:修改設定檔(永久,需記得改回)
echo 'skip-grant-tables' >> /etc/my.cnf.d/skip-grant.cnf
systemctl start mysqld

# 方法 B:手動啟動(臨時,建議)
mysqld_safe --skip-grant-tables --skip-networking &

# 3. 免密登入
mysql -u root

# 4. 更新密碼(MySQL 5.7+ 使用 authentication_string 欄位)
USE mysql;
UPDATE user SET authentication_string = PASSWORD('new_strong_pass') WHERE User = 'root';
FLUSH PRIVILEGES;

# 5. 恢復正常模式
# 若用方法 A:刪除 skip-grant.cnf 並重啟
# 若用方法 B:殺掉 mysqld_safe 進程,正常啟動
systemctl restart mysqld

Windows 環境詳細操作

# 1. 以管理員身分開啟 CMD,停止服務
net stop MySQL

# 2. 建立臨時設定檔或修改 my.ini
# 在 [mysqld] 區段加入 skip-grant-tables
notepad "C:\ProgramData\MySQL\MySQL Server 5.7\my.ini"

# 3. 啟動服務
net start MySQL

# 4. 免密登入
mysql -u root

# 5. 更新密碼(同 Linux)

# 6. 移除 skip-grant-tables,重啟服務
net stop MySQL
net start MySQL

MySQL 8.0+ 特別注意

MySQL 8.0 移除 PASSWORD() 函數,密碼更新語法變更:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_strong_pass';
-- 或
SET PASSWORD FOR 'root'@'localhost' = 'new_strong_pass';

且 skip-grant-tables 啟動時預設啟用 --skip-networking,僅允許本機 Unix socket 連線。

安全建議

  • 密碼長度 ≥ 12 字元,包含大小寫、數字、符號
  • 禁止 root 遠程登入(Host 設為 localhost 或 127.0.0.1)
  • 建立專用應用程式帳號,授予最小必要權限
  • 定期輪換密碼,使用密碼管理工具儲存
copyright © 萬盛學電腦網 all rights reserved