遺失 MySQL root 密碼是常見運維場景。本文提供標準的 --skip-grant-tables 繞過權限檢查重置密碼流程,適用於 Linux/Windows,並補充其他修改密碼方法供參考。
# Linux (Systemd)
systemctl stop mysqld
# 或 SysVinit
service mysqld stop
# 或直接殺進程
kill -TERM $(cat /var/run/mysqld/mysqld.pid)
# Windows (管理員 CMD)
net stop mysql
# 或任務管理員結束 mysqld.exe
# Linux
mysqld_safe --skip-grant-tables --skip-networking &
# --skip-networking 防止遠程連入,安全第一
# Windows (在安裝目錄 bin 下)
mysqld --skip-grant-tables --skip-networking
mysql -u root mysql
# 進入 mysql 命令列後執行:
UPDATE user SET authentication_string=PASSWORD('新密碼') WHERE User='root';
-- MySQL 5.7+ 欄位為 authentication_string,5.6 為 Password
FLUSH PRIVILEGES;
EXIT;
# Linux
systemctl stop mysqld # 先停掉 skip-grant-tables 的進程
systemctl start mysqld
# Windows
net stop mysql
net start mysql
| 方法 | 指令/操作 | 適用場景 |
|---|---|---|
| SET PASSWORD | SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass'); | 已登入 Shell、知舊密碼 |
| mysqladmin | mysqladmin -u root -p'oldpass' password 'newpass' | 命令列、知舊密碼 |
| UPDATE user 表 | UPDATE mysql.user SET authentication_string=PASSWORD('newpass') WHERE User='root'; FLUSH PRIVILEGES; | 有 root 權限登入 |
| phpMyAdmin | 介面操作 user 表 | 圖形化、知舊密碼 |
| GRANT ... IDENTIFIED BY | GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY 'newpass'; | 建立/修改用戶 |
authentication_string,舊版為 Password,請確認版本。--skip-networking 限制本機連線**,完成後立即正常重啟。validate_password 插件強制強密碼策略。掌握 --skip-grant-tables 重置流程,配合多種修改密碼方式,讓您從容應對 MySQL 密碼遺失危機。