CentOS/RHEL 系列 Linux 下 MySQL 密碼重置標準化操作流程,經 CentOS 7/8 + MySQL 5.7/8.0 實測驗證。採用 --skip-grant-tables 跳過授權表啟動,空密碼登錄,更新密碼,刷新權限,正常重啟五步法。
/var/lib/mysql,配置文件:/etc/my.cnfsystemctl stop mysqld
# 或舊版
service mysqld stop
# 方式一:mysqld_safe (推薦,自動監護重啟)
mysqld_safe --skip-grant-tables --skip-networking &
# 方式二:mysqld 直接啟動 (前台調試用)
mysqld --skip-grant-tables --skip-networking --user=mysql &
⚠️ 必加 --skip-networking:防止跳過授權期間外部連接入侵,僅允許本地 Socket 連接。
mysql -u root -p
# Enter password: 直接回車 (空密碼)
MySQL 5.7:
UPDATE mysql.user SET authentication_string = PASSWORD('NewStrongPass123') WHERE User = 'root';
FLUSH PRIVILEGES;
MySQL 8.0: (推薦 ALTER USER,自動處理 caching_sha2_password)
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123';
FLUSH PRIVILEGES;
⚠️ 8.0 若用 UPDATE 需同步更新 plugin 列為 caching_sha2_password,易出錯,**強烈建議用 ALTER USER**。
EXIT;
# 停止臨時實例
pkill -f "mysqld.*skip-grant-tables"
# 或
mysqladmin -u root -p'NewStrongPass123' shutdown
# 啟動正常服務
systemctl start mysqld
# 驗證
mysql -u root -p'NewStrongPass123' -e "SELECT 1;"
| 現象 | 原因 | 解決 |
|---|---|---|
ERROR 1045 即使用 skip-grant-tables | 未加 --skip-networking,連上了正常運行的實例 | 確認舊實例已停、新實例加 --skip-networking |
Unknown column 'password' | 5.7/8.0 密碼列為 authentication_string | 用版本對應 SQL,見上文 |
| 重置後無法啟動正常服務 | 臨時實例未完全停止、端口/鎖文件佔用 | pkill -9 mysqld、檢查 /var/run/mysqld/mysqld.pid、/var/lib/mysql/*.sock |
| SELinux 阻擋啟動 | CentOS 7/8 默認 Enforcing | setenforce 0 臨時放行、或配置 mysqld_t 上下文 |
# 1. 創建 SQL 文件
cat > /root/reset_root.sql <<'EOF'
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123';
FLUSH PRIVILEGES;
EOF
chmod 600 /root/reset_root.sql
# 2. 臨時 override 啟動參數
systemctl edit mysqld
# 添加:
[Service]
ExecStart=
ExecStart=/usr/sbin/mysqld --init-file=/root/reset_root.sql $@
# 3. 重啟生效
systemctl daemon-reload
systemctl restart mysqld
# 4. 驗證後移除 override
systemctl edit mysqld
# 刪除內容,保存
systemctl daemon-reload
systemctl restart mysqld
# 5. 清理 SQL 文件
shred -u /root/reset_root.sql
CentOS MySQL 密碼重置鐵律:停服務、skip-grant-tables+skip-networking、空密碼登、ALTER USER 改密、FLUSH PRIVILEGES、殺臨時啟正常、驗證新密碼。生產環境優先用 systemd --init-file 單次重啟方案,安全、可審計、可自動化。