Gentoo安裝MySQL後,root登入報錯:
Access denied for user 'root'@'localhost'
# 1. 停止 MySQL 服務
/etc/init.d/mysql stop
# 2. 以跳過權限檢查模式啟動 (僅本地、無網路)
mysqld_safe --user=mysql --skip-grant-tables --skip-networking &
# 3. 無密碼登入 root
mysql -u root mysql
# 4. 更新 root 密碼 (MySQL 5.7+ 使用 authentication_string)
UPDATE user SET Password=PASSWORD('yournewpasswd') WHERE User='root';
# 或 MySQL 5.7+
UPDATE user SET authentication_string=PASSWORD('yournewpasswd') WHERE User='root';
FLUSH PRIVILEGES;
QUIT
# 5. 正常重啟服務
/etc/init.d/mysql restart
# 管理員測試
mysqladmin -u root -p'yournewpasswd' ping
# mysqld is alive
# 客戶端登入
mysql -u root -p
# Enter password: yournewpasswd
# Welcome to MySQL monitor...
| 參數 | 作用 |
|---|---|
--user=mysql | 以 mysql 系統帳號執行 (安全最佳實踐) |
--skip-grant-tables | 完全跳過權限系統,允許無密碼登入 |
--skip-networking | 禁用 TCP/IP 連線,僅允許本地 Socket (安全隔離) |
& | 背景執行,釋放終端機 |
--skip-grant-tables 期間任何本地使用者可無密碼以 root 身分登入--skip-networking 防止遠端連線validate_password、設定密碼過期策略
# 1. 建立初始化檔
echo "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass');" > /tmp/mysql-init.sql
# 2. 重啟時載入
mysqld_safe --init-file=/tmp/mysql-init.sql &
# 3. 成功後刪除初始化檔
rm /tmp/mysql-init.sql