前置條件
- 從未設定root密碼 → 無需密碼登入 (但強烈建議立即設定)
- 已設定但遺忘 → 需重置流程
Windows 平台重置流程
方法一:init-file 法 (標準、安全) ⭐
# 1. 以系統管理員身分登入
# 2. 停止 MySQL 服務
# 服務管理器 (services.msc) → MySQL → 停止
# 或任務管理員強制結束 mysqld 進程
# 3. 建立初始化檔 C:\mysql-init.txt (單行)
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');
# 4. 命令提示字元 (管理員) 執行
# 標準安裝
C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld-nt.exe" --init-file=C:\mysql-init.txt
# MySQL Installer 安裝 (需指定 defaults-file)
C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld-nt.exe" \
--defaults-file="C:\Program Files\MySQL\MySQL Server 5.1\my.ini" \
--init-file=C:\mysql-init.txt
# 5. 服務啟動後刪除初始化檔
del C:\mysql-init.txt
# 6. 正常模式重啟服務 (服務管理器或 net start mysql)
方法二:skip-grant-tables 法 (通用、需重啟兩次)
# 1. 停止服務
# 2. 命令列啟動跳過權限
mysqld-nt --skip-grant-tables --user=root
# 3. 新視窗無密碼登入
mysql -u root
# 4. 更新密碼
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;
# 5. 關閉跳過權限的 mysqld (Ctrl+C)
# 6. 正常啟動服務
Linux/Unix 平台重置流程
方法一:init-file 法 (標準) ⭐
# 1. 以 root 或 mysqld 運行帳號登入
# 2. 找到 .pid 檔案 (常見位置)
/var/lib/mysql/hostname.pid
/var/run/mysqld/mysqld.pid
/usr/local/mysql/data/hostname.pid
# 3. 正常停止 (SIGTERM,非 kill -9)
kill `cat /var/lib/mysql/hostname.pid`
# 4. 建立初始化檔 ~/mysql-init
echo "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');" > ~/mysql-init
# 5. 啟動載入初始化檔
mysqld_safe --init-file=~/mysql-init &
# 6. 成功後刪除初始化檔
rm ~/mysql-init
方法二:skip-grant-tables 法
# 1. 停止 mysqld
# 2. 跳過權限啟動
mysqld_safe --skip-grant-tables --user=root &
# 3. 無密碼登入
mysql -u root
# 4. 更新密碼
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;
# 5. 重啟正常模式
關鍵差異對照表
| 項目 | Windows | Linux/Unix |
| 服務管理 | services.msc / net start | systemctl / /etc/init.d / mysqld_safe |
| 進程停止 | 任務管理員 / net stop | kill `cat pid_file` (SIGTERM) |
| 執行檔名 | mysqld-nt.exe / mysqld.exe | mysqld / mysqld_safe |
| 配置檔 | my.ini (安裝目錄) | my.cnf (/etc / /usr/local/etc) |
| Socket檔案 | 無 (Named Pipe/TCP) | /tmp/mysql.sock 或 datadir/mysql.sock |
通用安全建議
- 重置後立即驗證:
mysql -u root -p'newpass' -e "SELECT 1;"
- 檢查所有 root 帳號:
SELECT User, Host FROM mysql.user WHERE User='root';
- 移除匿名帳號:
DELETE FROM mysql.user WHERE User='';
- 限制 root 存取來源:
RENAME USER 'root'@'%' TO 'root'@'localhost';
- 啟用密碼驗證外掛:
INSTALL PLUGIN validate_password SONAME 'validate_password.so';