萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

修改 MySQL root 密碼 4 種方法:正常修改與忘記密碼緊急重置

涵蓋已知密碼的 3 種標準修改方式,與完全忘記密碼時的 skip-grant-tables 緊急重置流程。

已知舊密碼時

方法 1:mysqladmin 命令列 (最簡單)

mysqladmin -u root -p'old_pass' password 'new_pass'
# 或交互式
mysqladmin -u root -p password 'new_pass'

方法 2:UPDATE user 表 + FLUSH PRIVILEGES

mysql -u root -p
UPDATE mysql.user SET authentication_string=PASSWORD('new_pass') WHERE User='root';
FLUSH PRIVILEGES;

MySQL 5.7+ 欄位為 authentication_string,5.6 為 password。

方法 3:SET PASSWORD 語句

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_pass');
-- 5.7.6+ 也支援
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_pass';

忘記 root 密碼 — 緊急重置

  1. 停止服務:service mysqld stop / net stop MySQL
  2. 啟動跳過權限表:
    mysqld_safe --skip-grant-tables --skip-networking &
        # Windows: mysqld --console --skip-grant-tables --skip-networking
        
  3. 無密碼登入:mysql -u root
  4. 修改密碼:
    USE mysql;
    UPDATE user SET authentication_string=PASSWORD('new_pass') WHERE User='root';
    FLUSH PRIVILEGES;
        
  5. 正常重啟:service mysqld restart (移除 --skip-grant-tables)

安全建議

  • 密碼複雜度:≥12 字元、大小寫、數字、符號。
  • 禁止 root@%,僅允許 root@localhost 或 127.0.0.1。
  • 定期輪換,配合密碼管理工具儲存。
  • 5.7+ 建議啟用 validate_password 插件強制策略。
copyright © 萬盛學電腦網 all rights reserved