在安裝 MySQL 或 MariaDB 伺服器後, 當執行 mysql_secure_installation 後會完成一些基本的安全設定, 其中一項就是設定 root 的密碼。
如果在往後忘記了這個 MySQL root 密碼, 可以用以下方法重設, 以下文章會以 CentOS 環境作為例子.
首先將運行中的 MySQL Server 停止執行:
# systemctl stop mariadb
或
# systemctl stop mysql
或
# /etc/rc.d/init.d/mysqld stop
然後啟動 MySQL 並加入 skip-grant-tables 選項, 目的是可以用空密碼登入 MySQL 的 root 帳號:
1 2 |
# systemctl set-environment MYSQLD_OPTS="--skip-grant-tables" # systemctl start mariadb |
或
1 2 |
# systemctl set-environment MYSQLD_OPTS="--skip-grant-tables" # systemctl start mysql |
或
1 |
# mysqld_safe --skip-grant-tables & |
現在可以用空密碼直接登入 MySQL:
# mysql -u root
登入 MySQL Server 後, 用以下指令重設 MySQL 的 root 密碼, 將下面的 new-password 改成你想設定的新密碼:
1 2 3 4 |
MariaDB [(none)]> USE mysql; MariaDB [(none)]> UPDATE user SET password=PASSWORD('new-password') WHERE User='root' AND Host = 'localhost'; MariaDB [(none)]> FLUSH PRIVILEGES; MariaDB [(none)]> quit; |
現在可以重新啟動 MySQL Server:
1 2 3 |
# systemctl stop mariadb # systemctl unset-environment MYSQLD_OPTS # systemctl start mariadb |
或
1 2 3 |
# systemctl stop mysql # systemctl unset-environment MYSQLD_OPTS # systemctl start mysql |
或
1 |
# /etc/rc.d/init.d/mysql restart |
重新啟動 MySQL 後, 便可以用新設置的 root 密碼登入 MySQL.
無法正確重設的話可以參考這篇~
http://goodjack.blogspot.com/2018/02/mariadb-root.html