1. 首先确认服务器处于安全的状态,因为设置skip-grant-tables后Mysql数据库用户登录将跳过权限表的加载,可以任意地登录和修改MySQL的信息。
2.修改Mysql数据库 my.cnf 配置
# vi /etc/my.cnf
在[mysqld]的段中加上一句:skip-grant-tables ,保存并且退出;
[mysqld]
......
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
skip-grant-tables
3. 重启mysqld服务
# systemctl restart mysqld
4.登录mysql修改root密码
[root@localhost /]# mysql
......
mysql> update mysql.user set authentication_string=password('123456')
where host ='localhost' and user='root';
Query OK, 0 rows affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 1
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql>
注意:
MySQL 5.7的更新的是user表中authentication_string字段,
MySQL 5.6的更新的是user表中password字段,
update mysql.user set password=password('123456') where host='localhost' and user='root';
修改用户密码后使用命令:flush privileges更新用户权限。
5. 改回配置重启mysqld
[root@localhost /]# vi /etc/my.cnf
[root@localhost /]# systemctl restart mysqld
[root@localhost /]# mysql -uroot -p123456
......
mysql>
至此,忘记mysql root密码已解决。