【MySQL】MySQL root密码忘记解决方法


skip-grant-tables 解法

  1. 首先,要停止Mysql实例
# service mysqld stop/ service mysql.server stop/ /etc/init.d/mysql.init stop  ### 这几个方法都是一个意思
# killall mysqld
# kill -9 `pidof mysqld`
  1. 使用skip-grant-tables参数,启动实例
# vi /etc/my.cnf
添加如下内容
skip-grant-tables
skip-networking

设置了该参数,则实例在启动过程中会跳过权限表的加载,这就意味着任何用户都能登录进来,并进行任何操作,相当不安全。建议同时添加skip-networking

  1. 修改密码
# 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
or
mysql> update mysql.user set password=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> select * from mysql.user\G;
确认密码字段为authentication_string还是password进行使用对应的语句
  1. 重新启动mysql
# vi /etc/my.cnf
将以下内容
skip-grant-tables
skip-networking
修改为
#skip-grant-tables
#skip-networking
# service mysqld restart
  1. 验证密码修改是否生效
mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.24

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.
Type help; or ‘\h for help. Type ‘\c to clear the current input statement.
mysql>证明密码修改成功

通用解法

同样是建立在skip-grant-tables的条件上,可先通过flush privileges操作触发权限表的加载,再执行alter user操作。这种做法只适用于mysql-5.7以上。

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql>alter user 'root'@'localhost' identified by '123456';
Query OK, 0 rows affected (0.00 sec)

更为骚气的做法

  1. 首先,依旧是关闭实例
  2. 其次,创建一个sql文件
# vim init.sql 
写进如下内容:
alter user 'root'@'localhost' identified by '123456';
  1. 使用--init-file参数,启动实例
service mysqld restart --init-file=/root/init.sql 

注意:该操作只适用于/etc/init.d/mysqld这种服务管理方式,不适用于RHEL 7新推出的systemd。