萬盛學電腦網

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

MySQL 忘記 root 密碼找回:Windows/Linux 雙平台多種方案

MySQL root 密碼遺失?Windows/Linux 多種找回方案彙總

整合多種實戰可行方案,涵蓋跳過權限表、mysqladmin 修改、phpMyAdmin 查看配置、init-file 現代化方案,按環境與版本選擇最適合的方式。

快速判斷:能否用其他方式登入?

  • phpMyAdmin 能進 → config.inc.php 查看帳密
  • 應用程式能連 → 翻閱配置檔/環境變數
  • 其他 root 等權限帳號可用 → 直接登入改密
  • 以上皆無 → 必須跳過權限表

Windows 方案

方案 A:mysqld-nt --skip-grant-tables (經典)


net stop mysql
cd "C:\Program Files\MySQL\MySQL Server 5.x\bin"
mysqld-nt --skip-grant-tables --console
# 另開視窗
mysql -u root
USE mysql;
UPDATE user SET Password=PASSWORD('新密碼') WHERE User='root';  -- 5.6-
-- 或 5.7+
UPDATE user SET authentication_string=PASSWORD('新密碼') WHERE User='root';
FLUSH PRIVILEGES; EXIT;
# 關閉 mysqld-nt 視窗,net start mysql

方案 B:mysqladmin 直接修改 (無需登入 MySQL)


net stop mysql
cd "C:\Program Files\MySQL\MySQL Server 5.x\bin"
mysqld-nt --skip-grant-tables --console
# 另開視窗
mysqladmin -u root flush-privileges password "新密碼"
mysqladmin -u root -p shutdown  # 輸入新密碼確認
net start mysql

方案 C:MySQL 8.0+ --init-file (推薦)


# 1. 建立 init.sql
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '新密碼'; FLUSH PRIVILEGES;" > C:\temp\init.sql

# 2. 停止服務
net stop mysql

# 3. 啟動帶 init-file
"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe" --init-file=C:\temp\init.sql --console

# 4. 幾秒後 Ctrl+C 停止,正常啟動服務
net start mysql

Linux 方案

方案 A:mysqld_safe --skip-grant-tables (經典)


systemctl stop mysqld
mysqld_safe --skip-grant-tables --skip-networking &
mysql -u root
# 執行 UPDATE/FLUSH PRIVILEGES (參考版本差異表)
pkill mysqld_safe
systemctl start mysqld

方案 B:--init-file 官方標準方式 (MySQL 5.7+/8.0 推薦)


# 1. 建立 SQL
cat > /tmp/reset_root.sql <<'EOF'
ALTER USER 'root'@'localhost' IDENTIFIED BY '新密碼';
FLUSH PRIVILEGES;
EOF

# 2. 停止服務
systemctl stop mysqld

# 3. 啟動 (以 mysql 用戶、指定 datadir、socket)
/usr/sbin/mysqld --init-file=/tmp/reset_root.sql --user=mysql --datadir=/var/lib/mysql --socket=/var/run/mysqld/mysqld.sock &

# 4. 等待 5-10 秒,停止並正常啟動
pkill mysqld
systemctl start mysqld
rm -f /tmp/reset_root.sql

方案 C:systemd override 臨時修改啟動參數 (不動配置檔)


systemctl edit mysqld
# 輸入:
[Service]
ExecStart=
ExecStart=/usr/sbin/mysqld --skip-grant-tables --skip-networking $MYSQLD_OPTS

systemctl daemon-reload
systemctl start mysqld
# 修改密碼後
systemctl revert mysqld
systemctl daemon-reload
systemctl restart mysqld

版本差異速查表 (同前文)

MySQL 版本密碼欄位修改語法
≤ 5.6PasswordSET PASSWORD FOR 'root'@'localhost' = PASSWORD('pwd');
5.7authentication_stringUPDATE user SET authentication_string=PASSWORD('pwd') WHERE User='root';
8.0+authentication_stringALTER USER 'root'@'localhost' IDENTIFIED BY 'pwd';

phpMyAdmin 線索查找


# config.inc.php 或 config.default.php
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '實際密碼';

安全收尾 (必做)

  • 移除所有 --skip-grant-tables 啟動參數
  • 執行 mysql_secure_installation
  • 建立應用專用帳號,回收 root 遠程登入權限
  • 記錄新密碼至密碼管理器
copyright © 萬盛學電腦網 all rights reserved