在安装 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