萬盛學電腦網

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

MySQL Root 密碼重置與帳號恢復完整教學:Skip Grant Tables、初始化、權限刷新與安全加固

適用場景

  • 忘記 root 密碼。
  • 誤刪 root 帳號。
  • 權限表損壞導致無法登入。

步驟總覽

  1. 停止 MySQL 服務。
  2. 以 --skip-grant-tables 啟動(跳過權限檢查)。
  3. 免密登入,修改密碼或重建用戶。
  4. FLUSH PRIVILEGES 生效。
  5. 正常重啟 MySQL。

Windows 環境

net stop mysql
"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe" --skip-grant-tables --skip-networking
# 新開啟終端機
mysql -u root
-- 在 mysql> 提示符下
UPDATE mysql.user SET authentication_string = NULL WHERE User = 'root';
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
FLUSH PRIVILEGES;
EXIT;
# 關閉 --skip-grant-tables 進程,正常啟動服務
net start mysql

Linux 環境

systemctl stop mysqld
/usr/local/mysql/bin/mysqld_safe --skip-grant-tables --skip-networking --user=mysql &
mysql -u root
-- mysql> 內執行
UPDATE mysql.user SET authentication_string = '' WHERE User = 'root';
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
FLUSH PRIVILEGES;
EXIT;
killall mysqld_safe
systemctl start mysqld

MySQL 5.7 / 8.0 語法差異

版本密碼欄位設定密碼語法
5.7authentication_stringUPDATE ... SET authentication_string = PASSWORD('pwd')
8.0authentication_stringALTER USER 'root'@'localhost' IDENTIFIED BY 'pwd';

重建 Root 帳號(若被刪除)

CREATE USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;

安全加固建議

  1. 執行 mysql_secure_installation:移除匿名用戶、禁止遠端 root 登入、移除 test 庫。
  2. 使用強密碼策略(validate_password 插件)。
  3. 建立專用應用帳號,最小權限原則,禁用 root 應用連線。
  4. 啟用 SSL/TLS 加密傳輸。
  5. 定期審計 mysql.user、mysql.db 權限表。
copyright © 萬盛學電腦網 all rights reserved