首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

Gentoo Linux MySQL Root密碼重置實戰:skip-grant-tables緊急恢復指南

     編輯:MySQL 資料庫相關知識

問題現象

Gentoo安裝MySQL後,root登入報錯:

Access denied for user 'root'@'localhost'

根因

  • 初始化過程未正確設定root密碼
  • 或密碼遺失/未知
  • 權限表異常

標準重置流程 (skip-grant-tables 緊急模式)


# 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、設定密碼過期策略

替代方案:init-file 法 (不需停機跳過權限)


# 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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved