首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL Root 密碼遺失?五分鐘重置全流程

     編輯:MySQL 資料庫相關知識

適用場景

  • Root 密碼遺忘、離職交接未留存、測試環境長期未用導致忘記。
  • MySQL 5.6 / 5.7 / 8.0 通用(步驟微差,文中標註)。

標準重置流程(跳過權限表啟動)

1. 停止 MySQL 服務

# Systemd (CentOS 7+, Ubuntu 16.04+)
systemctl stop mysqld
# 或
systemctl stop mysql

# SysVinit
service mysqld stop
# 或
/etc/init.d/mysql stop

2. 以跳過授權表模式啟動

# 前台運行(調試方便,新開終端操作後續步驟)
mysqld_safe --skip-grant-tables --skip-networking &

# 8.0 需顯式指定 --skip-grant-tables 後仍需 flush privileges
# 某些發行版需建立運行目錄
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

關鍵參數:

  • --skip-grant-tables:跳過權限表驗證,任意用戶無密碼登入。
  • --skip-networking:禁用 TCP/IP 連接,防止外部趁機入侵(僅允許本地 Unix Socket)。

3. 無密碼登入並修改密碼

mysql -u root

MySQL 5.7.6+ / 8.0:

-- 8.0 首先需刷新權限(skip-grant-tables 下表可寫但權限未加載)
FLUSH PRIVILEGES;

-- 修改密碼(推薦 ALTER USER)
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';

-- 或 UPDATE 兼容舊版
UPDATE mysql.user SET authentication_string = '' WHERE User = 'root' AND Host = 'localhost';
-- 8.0 authentication_string 列存儲哈希,PASSWORD() 已棄用
-- 手動生成哈希(若必要):
-- SELECT CONCAT('*', UPPER(SHA1(UNHEX(SHA1('NewStrongPass123!')))));
FLUSH PRIVILEGES;

MySQL 5.6 / 5.7.5 及更早:

UPDATE mysql.user SET Password = PASSWORD('NewStrongPass123!') WHERE User = 'root';
FLUSH PRIVILEGES;

4. 正常重啟服務

# 關閉臨時實例
mysqladmin -u root -p shutdown
# 輸入新密碼

# 正常啟動
systemctl start mysqld
# 或
systemctl start mysql

5. 驗證新密碼

mysql -u root -p'NewStrongPass123!' -e "SELECT VERSION();"

Windows 環境圖解步驟

  1. 以管理員身份打開 CMD / PowerShell。
  2. net stop mysql(或服務管理器停止)。
  3. cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"(按實際路徑)。
  4. mysqld --console --skip-grant-tables --skip-networking(保持窗口開啟)。
  5. 新開窗口:mysql -u root → 執行上述 SQL 修改密碼。
  6. Ctrl+C 關閉第一個窗口 → net start mysql。

常見坑與應對

現象原因解決
ERROR 1290: The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement 8.0 skip-grant-tables 下禁止 DDL/DML 先執行 FLUSH PRIVILEGES; 再改密碼
修改後仍無法登入 Host 不匹配(如 'root'@'127.0.0.1' vs 'root'@'localhost') 檢查 SELECT User, Host FROM mysql.user; 全部 root 賬號同步修改
mysqld_safe 報錯目錄不存在 PID 文件目錄缺失 mkdir -p /var/run/mysqld && chown mysql:mysql /var/run/mysqld
Windows 下 mysqld --console 閃退 配置文件 my.ini 路徑錯誤或數據目錄權限 指定 --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini"

總結

Root 密碼重置核心在於 「停服務 → skip-grant-tables 啟動 → 免密登入 → 改密 → 正常重啟」。全程約 3 分鐘。生產環境操作前請確認:已通知相關方、備份關鍵數據、關閉外部訪問(防火牆/安全組)。事後建議立即啟用密碼輪換策略、配置審計日誌、納入密碼管理平台(如 Vault、1Password 團隊版)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved