| 方案 | 適用場景 | 風險 | 停機時間 | 推薦指數 |
|---|---|---|---|---|
| 複製已知授權表檔案 | 同版本、同架構、有可用備份實例 | 版本不匹配導致啟動失敗、權限表結構差異 | 短 (重啟一次) | ⭐⭐ |
--skip-grant-tables (標準) | **所有場景通用**、無備份實例 | 短暫無授權狀態 (需 --skip-networking 緩解) | 短 (重啟兩次) | ⭐⭐⭐⭐⭐ |
| 十六進位編輯 user.MYD | 極端情況 (無法啟動、無備份) | 極高:易損壞索引、位移計算錯誤、InnoDB 不適用 | 長 | ⭐ |
--skip-grant-tables 企業級 SOP# 1. 停止服務 (優雅關閉)
systemctl stop mysqld
# 或
mysqladmin -u root -p shutdown
# 2. 啟動無授權、無網路模式 (僅本地 Unix socket)
mysqld_safe --skip-grant-tables --skip-networking --socket=/var/run/mysqld/mysqld.sock --datadir=/var/lib/mysql &
※ --skip-networking **必加**,防止無授權狀態下被任意連線。
# 3. 本地無密碼登入
mysql -u root -S /var/run/mysqld/mysqld.sock mysql
# 4. 更新密碼 (MySQL 5.7+ authentication_string 欄位)
UPDATE user SET authentication_string=PASSWORD('NewStrongPass#2024'), password_expired='N', password_last_changed=NOW() WHERE User='root';
FLUSH PRIVILEGES;
# 5.7 以前版本
UPDATE user SET Password=PASSWORD('NewStrongPass#2024') WHERE User='root';
FLUSH PRIVILEGES;
# 5. 關閉無授權實例
mysqladmin -u root -S /var/run/mysqld/mysqld.sock shutdown
# 6. 正常啟動
systemctl start mysqld
# 7. 驗證新密碼
mysql -u root -p'NewStrongPass#2024' -e "SELECT VERSION();"
systemctl stop mysqldmv /var/lib/mysql/mysql /var/lib/mysql/mysql.bak_$(date +%F)mysql 目錄 (含 *.frm, *.ibd, *.MYD, *.MYI, *.sdi)。chown -R mysql:mysql /var/lib/mysql/mysql && chmod -R 750 /var/lib/mysql/mysql && find /var/lib/mysql/mysql -name "*.ibd" -exec chmod 660 {} \;USE mysql;
UPDATE user SET authentication_string=PASSWORD('NewStrongPass#2024') WHERE User='root';
DELETE FROM user WHERE User='';
DELETE FROM user WHERE Host='%';
FLUSH PRIVILEGES;
authentication_string 儲存雜湊,plugin 欄位指定驗證插件 (caching_sha2_password 預設 / mysql_native_password)。ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass#2024'; (需授權表生效時)。--skip-grant-tables 模式下無法使用 ALTER USER,必須直接 UPDATE user 表並手動設定 plugin。CREATE USER 'dba'@'10.0.0.%' IDENTIFIED BY '...' REQUIRE SSL; GRANT ALL ON *.* TO 'dba'@'10.0.0.%' WITH GRANT OPTION;DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost','127.0.0.1','::1'); FLUSH PRIVILEGES;INSTALL PLUGIN audit_log SONAME 'audit_log.so';