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

CentOS MySQL 忘記 Root 密碼導致無法登入的兩種解決方案

     編輯:MySQL 資料庫相關知識

CentOS 上 MySQL/MariaDB 忘記 root 密碼,無法登入執行 mysql_secure_installation。本文提供兩種實測可用的重置方案:跳過授權表啟動 與 Debian 維護帳號。

方案一:--skip-grant-tables 臨時跳過權限驗證

# 1. 停止服務
systemctl stop mysqld

# 2. 以跳過授權表模式啟動 (後台運行)
mysqld_safe --user=mysql --skip-grant-tables --skip-networking &

# 3. 無密碼登入並修改密碼
mysql -u root mysql
UPDATE user SET authentication_string=PASSWORD('newpassword') WHERE User='root';
FLUSH PRIVILEGES;
QUIT

# 4. 正常重啟服務
systemctl restart mysqld

# 5. 新密碼登入驗證
mysql -u root -p
# 輸入 newpassword

注意:MySQL 5.7+ 密碼欄位為 authentication_string,5.6 為 Password;請根據版本調整 SQL。

方案二:使用 debian-sys-maint 維護帳號 (Debian/Ubuntu 專用)

Debian 系安裝 MySQL 會自動建立維護帳號,密碼存於 /etc/mysql/debian.cnf。

# 1. 讀取帳號密碼
cat /etc/mysql/debian.cnf
# [client]
# user = debian-sys-maint
# password = xxxxxxxx

# 2. 以維護帳號登入
mysql -u debian-sys-maint -p
# 輸入上述密碼

# 3. 修改 root 密碼
UPDATE mysql.user SET authentication_string=PASSWORD('newpassword') WHERE User='root';
FLUSH PRIVILEGES;
QUIT

# 4. 新密碼驗證
mysql -u root -p

適用場景對比

方案適用系統優點缺點
skip-grant-tables所有 Linux (RHEL/CentOS/Debian/Ubuntu)通用、無需額外帳號需停機、短暫無認證風險 (--skip-networking 緩解)
debian-sys-maintDebian/Ubuntu無需停機、不影響業務僅限 Debian 系、需讀取配置檔權限

事後建議

  • 密碼管理:使用密碼管理器或 /root/.my.cnf 存儲 root 密碼 (權限 600)。
  • 定期演練:每季執行一次密碼重置演練,確保流程熟悉。
  • 審計:啟用 log_warnings=2 記錄登入失敗,配合 Fail2Ban 防暴力破解。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved