Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 系統下重置 MySQL Root 密碼的完整指南

編輯:Linux 教學

在安裝 MySQL 時,系統通常會要求設定 root 使用者的密碼。但若不慎遺忘密碼,便需透過特定手段重置。本文整理四種常見且有效的重置方法,適用於各類 Linux 發行版。

方法一:使用 mysqladmin 指令

若已知現有密碼或無密碼可直接登入,可使用 mysqladmin 快速修改:

# mysqladmin -u root password 'newpassword'
# mysqladmin -u root -h host_name password 'newpassword'

說明:mysqladmin 通常位於 /usr/bin;host_name 為實際主機名稱(如 localhost.localdomain)。密碼若含空格或特殊符號,建議加上引號。

方法二:透過 SET PASSWORD SQL 指令

登入 MySQL 後執行:

# mysql -u root
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpassword');
mysql> SET PASSWORD FOR 'root'@'host_name' = PASSWORD('newpassword');

此法需具備 root 登入權限,適合已知密碼或免密登入的情況。

方法三:直接更新 user 表

同樣需先登入 MySQL:

# mysql -u root
mysql> UPDATE mysql.user SET Password = PASSWORD('newpassword') WHERE User = 'root';
mysql> FLUSH PRIVILEGES;

修改完畢務必執行 FLUSH PRIVILEGES 使變更生效。

方法四:以安全模式略過權限表重置(忘記密碼通用)

此為最常用的「忘記密碼」解決方案,步驟如下:

1. 停止 MySQL 服務

/etc/init.d/mysql stop

服務腳本路徑可能為 /etc/init.d/mysqld,視發行版而定。不建議使用 killall -TERM mysqld 強制終止。

2. 以 --skip-grant-tables 參數啟動

mysqld_safe --skip-grant-tables &

或導向空裝置避免輸出干擾:

mysqld_safe --skip-grant-tables >/dev/null 2>&1 &

mysqld_safe 通常位於 /usr/local/mysql/bin/。

3. 免密登入 MySQL

mysql -u root
# 或指定完整路徑
/usr/local/mysql/bin/mysql -u root mysql

4. 修改密碼並刷新權限

USE mysql;
SELECT host, user, password FROM user;
UPDATE user SET password=PASSWORD("newpassword") WHERE user="root";
FLUSH PRIVILEGES;

5. 重啟 MySQL 服務

service mysqld restart
# 或
/etc/init.d/mysql restart

完成上述步驟後,即可使用新密碼正常登入 MySQL。

Copyright © Windows教程網 All Rights Reserved