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

Linux 下 MySQL root 密碼忘記三種重置方案:skip-grant-tables 實戰詳解

     編輯:MySQL 資料庫相關知識

核心原理

啟動 MySQL 時跳過權限表 (skip-grant-tables),以空密碼 root 登入,更新 mysql.user 表的 authentication_string (5.7+) 或 Password (5.6-) 欄位,重啟恢復正常驗證。

方案一:修改 my.cnf (通用、持久化配置)

# 1. 確保安全:關閉對外端口、停止應用、最佳在主控台操作
# 2. 編輯配置
vi /etc/my.cnf
# [mysqld] 段下添加
skip-grant-tables
# 3. 重啟
systemctl restart mysqld   # 或 service mysqld restart
# 4. 免密登入並改密
mysql -u root
UPDATE mysql.user SET authentication_string=PASSWORD('NewPwd123!') WHERE User='root';
FLUSH PRIVILEGES;
EXIT;
# 5. 移除 skip-grant-tables 並重啟
vi /etc/my.cnf  # 刪除該行
systemctl restart mysqld
# 6. 驗證新密碼
mysql -u root -p'NewPwd123!'

方案二:命令列臨時啟動 (無需改配置、適合臨時救援)

# 1. 停止服務
systemctl stop mysqld
# 2. 後台啟動跳過權限
mysqld_safe --skip-grant-tables &
# 3. 免密登入改密 (同方案一步驟 4)
# 4. 正常重啟
systemctl restart mysqld

方案三:無 mysqld_safe 系統 (如 Ubuntu apt 安裝)

systemctl stop mysql
mysqld --skip-grant-tables &
mysql -u root
UPDATE mysql.user SET authentication_string=PASSWORD('NewPwd123!') WHERE User='root';
FLUSH PRIVILEGES;
EXIT;
systemctl restart mysql

5.7+ 關鍵差異

  • 密碼欄位改為 authentication_string (長文本),Password 欄位廢棄。
  • PASSWORD() 函數在 8.0 移除,建議用 ALTER USER 'root'@'localhost' IDENTIFIED BY 'pwd'; (需正常驗證模式下)。
  • FLUSH PRIVILEGES; 必須執行,否則修改不生效。

安全警示

skip-grant-tables 期間資料庫完全無保護,任何人可無密登入並任意增刪改查。務必:
1. 防火牆封鎖 3306 對外。
2. 停止所有應用服務。
3. 操作完成 立即 移除參數並重啟。

驗證腳本

# 一鍵驗證新密碼
mysql -uroot -p'NewPwd123!' -e "SELECT USER(), CURRENT_USER();"

三種方案覆蓋主流 Linux 發行版,收藏備用,關鍵時刻救命。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved