环境: redhat 7.4
一、停止mysqld服务,并修改配置文件
vim /etc/my.cnf
在[mysqld]的最后新增一行:skip-grant-tables
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
skip-grant-tables
二、重启mysqld,并用mysql命令登陆,这时会免密登陆,但是很多常用命令无法执行,好像是有权限控制。
systemctl restart mysqld
mysql -u root -p
//直接回车
mysql
//或者直接输入 mysql
三、修改mysql的root密码:
mysql>show databases;
mysql>use mysql;
mysql> select host, user, authentication_string, plugin from user;
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
| host | user | authentication_string | plugin |
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | root | $A$005$7
\S|G(Y?K?\hXfzjOVyQAYFkFWI5EXxDigxaKfakZ8LachbxQWr41MAyGE. | caching_sha2_password |
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
4 rows in set (0.00 sec)
字段解释:
host: 允许用户登录的ip‘位置’%表示可以远程;
user:当前数据库的用户名;
authentication_string: 用户密码;在mysql 5.7.9以后废弃了password字段和password()函数;
plugin: 密码加密方式;
如果当前root用户authentication_string字段下有内容,先将其设置为空;
mysql> update user set authentication_string='' where user='root';
//执行其它命令会报错,如:
mysql> set password="";
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
重新修改my.cnf配置文件,将删除或者注释刚才添加的skip-grant-tables并重新启动mysqld服务。
vim /etc/my.cnf
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
#skip-grant-tables
systemctl restart mysqld
四、重新登陆mysql登陆数据库
这个时候因为已经将root用户的密码字段authentication_string设置为空,可以不需要密码登陆。登陆mysql并修改密码。
mysql>use mysql;
mysql> select host, user, authentication_string, plugin from user;
//可以看到root的密码为空
mysql> ALTER user 'root'@'localhost' IDENTIFIED BY 'Test@1234'
//或者
mysql> set password="Test@1234";
退出并使用新密码重新登陆。
其他tips:
在第三步中,重新设置authentication_string字段的时候,如果不设置空,而设置某个值,比如:
mysql> update user set authentication_string='Test@1234' where user='root';
这时重新登陆mysql时会因为密码不正确被拒绝登陆,因为密码不正确。原因是:authentication_string字段下只能是mysql加密后的41位字符串密码,所以一定不能采用直接赋值的方法去修改用户密码,第四步中也同样不能使用,重新破解后查看用户的authentication_string就清楚了。