萬盛學電腦網

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

忘記 MySQL root 密碼?Linux / Windows 通用重置指南

核心原理

以 --skip-grant-tables 啟動 MySQL,跳過權限檢查,以 root 免密登入,更新 mysql.user 表的 authentication_string(5.7+)或 Password(5.6 及舊版),再刷新權限並正常重啟。

Linux 環境操作步驟

  1. 編輯 /etc/my.cnf,在 [mysqld] 區段加入:
    skip-grant-tables
  2. 重啟服務:
    systemctl restart mysqld
  3. 免密登入:
    mysql -u root
  4. 更新密碼(MySQL 5.7+ / 8.0):
    USE mysql;
    UPDATE user SET authentication_string = PASSWORD('NewPass123!') WHERE User = 'root';
    FLUSH PRIVILEGES;
  5. MySQL 5.6 或舊版:
    UPDATE user SET Password = PASSWORD('NewPass123!') WHERE User = 'root';
    FLUSH PRIVILEGES;
  6. 移除 skip-grant-tables,重啟服務:
    systemctl restart mysqld
  7. 驗證新密碼:
    mysql -u root -p'NewPass123!'

Windows 環境操作步驟

  1. 以管理員身分開啟 CMD,停止服務:
    net stop mysql
  2. 進入安裝目錄 bin,跳過權限啟動:
    mysqld --skip-grant-tables --console
    (視窗保持開啟,勿關閉)
  3. 新開 CMD 視窗,免密登入:
    mysql -u root
  4. 更新密碼(同 Linux 步驟 4)。
  5. 關閉第一個視窗(Ctrl+C 停止 mysqld),正常啟動服務:
    net start mysql
  6. 驗證新密碼。

MySQL 8.0 特殊處理

8.0 預設使用 caching_sha2_password 插件,若客戶端不支援,需同步指定:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'NewPass123!';
FLUSH PRIVILEGES;

單用戶模式替代方案(Linux)

若無法修改 my.cnf,可在 GRUB 啟動參數加入 init=/bin/bash 進入單用戶模式,掛載根分區為可寫,直接編輯 my.cnf 或用 mysqladmin 修改密碼。

安全建議

  • 重置後立即執行 mysql_secure_installation 移除匿名帳號、禁止 root 遠端登入、移除 test 資料庫。
  • 使用密碼管理器儲存強密碼,避免再次遺忘。
copyright © 萬盛學電腦網 all rights reserved