遇到 ERROR 1045 (28000): Access denied for user 'root'@'localhost' 時,提供三種經驗證的重置方案,涵蓋 Ubuntu/Debian/CentOS/RHEL 等主流發行版。
# 1. 停止服務
systemctl stop mysqld
# 或 service mysql stop
# 2. 啟動跳過授權表模式 (後台運行)
mysqld_safe --skip-grant-tables --skip-networking &
# 3. 免密登入
mysql -u root mysql
# 4. 修改密碼
-- MySQL 5.7.6+ / 8.0 (authentication_string 列)
UPDATE user SET authentication_string=PASSWORD('newpass') WHERE User='root';
FLUSH PRIVILEGES;
-- MySQL 5.7.5 及之前 (password 列)
UPDATE user SET password=PASSWORD('newpass') WHERE User='root';
FLUSH PRIVILEGES;
-- MySQL 8.0.4+ 推薦語法 (PASSWORD() 已移除)
ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpass';
FLUSH PRIVILEGES;
# 5. 正常重啟
systemctl restart mysqld
# 驗證
mysql -u root -p'newpass'
Debian 系安裝 MySQL 時自動創建 debian-sys-maint 用戶,密碼存於 /etc/mysql/debian.cnf,擁有完全權限。
# 1. 讀取密碼
cat /etc/mysql/debian.cnf
# [client]
# user = debian-sys-maint
# password = xxxxxxxx
# 2. 登入修改
mysql -u debian-sys-maint -p'xxxxxxxx' mysql
UPDATE user SET authentication_string=PASSWORD('newpass') WHERE User='root';
FLUSH PRIVILEGES;
QUIT;
# 3. 驗證
mysql -u root -p'newpass'
# 某些安裝腳本會將 root 密碼同步設置為 debian-sys-maint 密碼
mysql -u root -p'xxxxxxxx' # 使用 debian.cnf 中的 password
# 若成功登入,立即修改密碼
ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpass';
注意: 此法不通用,僅作嘗試。
| 版本 | 密碼列 | 修改語法 | PASSWORD() |
|---|---|---|---|
| 5.6 / 5.7.5- | password | UPDATE user SET password=PASSWORD('x') | 支援 |
| 5.7.6+ | authentication_string | UPDATE user SET authentication_string=PASSWORD('x') | 支援 |
| 8.0.4- | authentication_string | UPDATE user SET authentication_string=PASSWORD('x') | 支援 |
| 8.0.11+ | authentication_string | ALTER USER 'root'@'localhost' IDENTIFIED BY 'x' | 移除 |
mysqld --skip-grant-tables --skip-networking & 或確認 PATH 包含 bin 目錄。--skip-networking 是否導致本地 socket 連接失效,嘗試 mysql -u root --protocol=socket。--skip-grant-tables 模式下無需執行,直接退出重啟即可。