接手伺服器發現無 root 密碼文檔,需重置。核心手段:啟動 mysqld 時加入 --skip-grant-tables 繞過權限驗證,免密登入修改 mysql.user 表。
sed -i '/\[mysqld\]/a\skip-grant-tables' /etc/my.cnf
service mysqld restart # 或 systemctl restart mysqld
mysql -u root
USE mysql;
-- MySQL 5.6/5.7
UPDATE user SET Password = PASSWORD('NewStrongP@ssw0rd!') WHERE User = 'root';
-- MySQL 8.0 (authentication_string)
UPDATE user SET authentication_string = '' WHERE User = 'root';
FLUSH PRIVILEGES;
QUIT;
sed -i '/skip-grant-tables/d' /etc/my.cnf service mysqld restart
mysql -u root -p'NewStrongP@ssw0rd!' # 登入成功即完成
8.0 移除 Password 欄位,改用 authentication_string。skip-grant-tables 下無法執行 ALTER USER,需分兩階段:
skip-grant-tables 模式下 UPDATE authentication_string = '' 清空密碼。ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongP@ssw0rd!'; 設定強密碼。# 1. 建立 SQL 腳本 echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongP@ssw0rd!';" > /tmp/reset_root.sql # 2. 啟動時載入 mysqld --init-file=/tmp/reset_root.sql --user=mysql & # 3. 正常登入驗證後,移除 init-file 參數重啟
此法避免修改全域配置,安全性稍高。
DELETE FROM mysql.user WHERE User='root' AND Host='%'; FLUSH PRIVILEGES;ALTER USER 'root'@'localhost' PASSWORD EXPIRE INTERVAL 90 DAY;