首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL 忘記 Root 密碼?跳過授權表重置密碼全平台指南 (Windows/Linux)

     編輯:MySQL 綜合教學

核心原理

以 --skip-grant-tables 啟動 MySQL,跳過權限檢查,無密碼登入,修改 mysql.user 表,刷新權限,重啟正常模式。

Windows 環境

REM 1. 以管理員身份打開 CMD,停止服務
sc stop mysql

REM 2. 跳過授權表啟動 (保持窗口開啟)
mysqld --skip-grant-tables

REM 3. 新開 CMD 窗口,無密碼登入
mysql -u root -p
-- 直接回車進入

REM 4. 修改密碼
USE mysql;
UPDATE user SET authentication_string=PASSWORD('123456') WHERE User='root';
-- MySQL 5.7+ 用 authentication_string,5.6 用 Password
FLUSH PRIVILEGES;
EXIT;

REM 5. 關閉兩個窗口,正常啟動服務
sc start mysql

REM 6. 驗證新密碼
mysql -u root -p123456

Linux 環境 (Systemd / SysVinit 通用)

# 1. 停止服務
systemctl stop mysqld
# 或: /etc/init.d/mysql stop

# 2. 跳過授權表啟動 (後台運行)
mysqld_safe --skip-grant-tables &

# 3. 無密碼登入
mysql -u root

# 4. 修改密碼 (同 Windows)
USE mysql;
UPDATE user SET authentication_string=PASSWORD('123456') WHERE User='root';
FLUSH PRIVILEGES;
EXIT;

# 5. 關閉臨時進程,正常啟動
pkill mysqld
systemctl start mysqld
# 或: /etc/init.d/mysql start

# 6. 驗證
mysql -u root -p123456

版本差異提醒

版本密碼欄位語法
MySQL 5.6PasswordUPDATE user SET Password=PASSWORD('new') ...
MySQL 5.7 / 8.0authentication_stringUPDATE user SET authentication_string=PASSWORD('new') ...
MySQL 8.0.11+authentication_string建議 ALTER USER 'root'@'localhost' IDENTIFIED BY 'new'; (需正常模式)

MySQL 8.0 現代重置法 (無需 skip-grant-tables)

# 1. 建立初始化文件 /tmp/init.sql
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPass123!';

# 2. 啟動時載入
mysqld --init-file=/tmp/init.sql --user=mysql &

# 3. 登入驗證
mysql -u root -pNewPass123!

安全建議

  • 重置後立即執行 mysql_secure_installation
  • 禁用 root@'%',建立專用業務帳號、最小權限
  • 密碼策略:長度≥12、大小寫數字特殊字符、定期輪換
  • 生產環境啟用 validate_password 插件強制複雜度

常見坑

  • ❌ 修改密碼後忘記 FLUSH PRIVILEGES → 新密碼不生效
  • ❌ --skip-grant-tables 未完全關閉舊進程 → 端口衝突、數據損壞
  • ❌ Windows 路徑含空格未加引號 → 啟動失敗
  • ❌ SELinux/AppArmor 阻擋 mysqld 讀寫 datadir → 查看 audit.log
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved