CentOS 上 MySQL/MariaDB 忘記 root 密碼,無法登入執行 mysql_secure_installation。本文提供兩種實測可用的重置方案:跳過授權表啟動 與 Debian 維護帳號。
# 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 系安裝 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-maint | Debian/Ubuntu | 無需停機、不影響業務 | 僅限 Debian 系、需讀取配置檔權限 |
/root/.my.cnf 存儲 root 密碼 (權限 600)。log_warnings=2 記錄登入失敗,配合 Fail2Ban 防暴力破解。