目录

MySQL 忘记 root 密码后进行重置

前段时间在 Vagrant 中安装了 CentOS 7.2 系统,然后部署了一套 lnmp 环境,数据库安装了 MariaDB 10.3.4,安装完成后,随机生成了一个 MariaDB 密码,后来就把这事给忘了。今天闲来无事,准备导入一些数据时悲剧了。密码早就忘的一干二净了,唉,郁闷呀,于是就想起来重置一下密码。

具体操作

停止服务

1
2
// 停止 MariaDB 服务
$ sudo systemctl stop mariadb.service

添加配置

MariaDB 的配置文件中 [mysqld] 后面添加如下两项配置:

1
2
3
4
5
6
$ sudo vim /etc/my.cnf.d/server.cnf
[mysqld]
...

skip-grant-tables
skip-networking
信息
  • skip-grant-tables: 此选项允许任何人不需密码登陆 MariaDB 数据库并且拥有所有特权,但是它禁止了账户管理命令如:ALTER USERSET PASSWORD
  • skip-networking: 此选项不允许远程客户端连接数据库

启动服务

1
2
// 启动 MariaDB 服务
$ sudo systemctl start mariadb.service

使用客户端连接数据库服务器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$ mysql -uroot
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.4-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

修改密码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
MariaDB [(none)]> USE mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> UPDATE user SET password=PASSWORD('your password') \
    -> WHERE User='root';
Query OK, 0 rows affected (0.000 sec)
Rows matched: 3  Changed: 0  Warnings: 0

MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.000 sec)

MariaDB [mysql]> exit;

移除配置并重启服务

将刚才添加的配置从配置文件移除掉

1
$ sudo systemctl restart mariadb.service

测试登录

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.3.4-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

参考