通過 跳過權限表驗證 (--skip-grant-tables) 啟動 MySQL 實例,以無密碼 Root 身份登錄,修改 mysql.user 表或執行 SET PASSWORD,刷新權限後重啟實例生效。
MySQL 服務。bin 目錄 (如 D:\MySQL\MySQL Server 5.7\bin)。mysqld --console --skip-grant-tables --shared-memory保持此窗口開啟 (關閉即停止實例)。
mysql -u root
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
-- 或 5.6 版本
UPDATE mysql.user SET authentication_string=PASSWORD('NewStrongPass123!') WHERE User='root' AND Host='localhost';
FLUSH PRIVILEGES;systemctl stop mysqld # 編輯服務文件 systemctl edit mysqld # 在 [Service] 區段添加 ExecStartPre= ExecStartPre=/usr/bin/mysqld_pre_systemd ExecStart= ExecStart=/usr/sbin/mysqld --skip-grant-tables --user=mysql $MYSQLD_OPTS # 保存退出 systemctl daemon-reload systemctl start mysqld # 無密碼登錄修改密碼 (同 Windows 步驟 5) # 修改完成後,撤銷上面的修改 (systemctl edit 刪除添加的內容),daemon-reload 並 restart
# 1. 停止服務
systemctl stop mysqld # 或 service mysql stop
# 2. 創建數據目錄權限臨時目錄 (防止 socket 找不到)
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
# 3. 後台啟動跳過授權
mysqld_safe --skip-grant-tables --skip-networking & # --skip-networking 僅本地登錄,更安全
# 等待幾秒確認啟動
# 4. 無密碼登錄
mysql -u root
# 5. 修改密碼 (同步刷新權限)
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass123!';
-- 5.7 以下版本
UPDATE mysql.user SET authentication_string=PASSWORD('NewStrongPass123!') WHERE User='root';
FLUSH PRIVILEGES;
# 6. 關閉臨時實例
mysqladmin -u root -p'NewStrongPass123!' shutdown
# 或 kill `cat /var/run/mysqld/mysqld.pid`
# 7. 正常啟動
systemctl start mysqld
password 列已重命名為 authentication_string。caching_sha2_password,若客戶端不支援,需指定:ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'NewStrongPass123!';
FLUSH PRIVILEGES 在 --skip-grant-tables 模式下必須執行,否則修改不生效。DELETE FROM mysql.user WHERE User='root' AND Host!='localhost'; FLUSH PRIVILEGES;