systemctl stop mysqld
# 或 service mysql stop
# 建立臨時目錄供 socket 使用
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
# 後台啟動
mysqld_safe --skip-grant-tables --skip-networking &
--skip-networking 防止外部連入,安全第一。
mysql -u root
# 進入 mysql> 提示符
-- MySQL 5.7 / MariaDB
UPDATE mysql.user SET authentication_string = PASSWORD('NewStrongPass123!') WHERE User = 'root';
FLUSH PRIVILEGES;
-- MySQL 8.0(authentication_string 欄位改為 auth_string,且預設 caching_sha2_password)
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'NewStrongPass123!';
FLUSH PRIVILEGES;
# 關閉 skip-grant-tables 進程
mysqladmin -u root -p shutdown
# 輸入新密碼
# 正常啟動
systemctl start mysqld
mysql -u root -p'NewStrongPass123!' -e "SELECT VERSION();"
caching_sha2_password,舊版客戶端可能不支援,建議改為 mysql_native_password(如上 ALTER USER 所示)。ERROR 1820 (HY000): You must reset your password using ALTER USER,說明密碼策略要求修改,直接用 ALTER USER 重置即可。# 1. 建立初始化檔
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPass123!';" > /tmp/mysql-init.sql
# 2. 啟動參數指定 init-file
mysqld --init-file=/tmp/mysql-init.sql --user=mysql &
# 3. 登入驗證後移除 init-file 正常重啟
DELETE FROM mysql.user WHERE User='';UPDATE mysql.user SET Host='localhost' WHERE User='root';DROP DATABASE test; DELETE FROM mysql.db WHERE Db='test%';FLUSH PRIVILEGES;