环境
centos 7.x
MySQL 5.7.20
前提
- 1.MySQL 可以重启
- 2.可以登录服务器
操作
- 1.原密码
[root@1]# mysql -uroot -p12345
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 4
Server version: 5.7.20-log MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
(root@localhost) [(none)]>
- 2.假设密码忘记
- 1.配置 my.cnf
vim /etc/my.cnf // 注意每个配置文件不一定位置相同
[mysqld]
skip-grant-tables // 写入 my.cnf 配置文件
- 2.重启 MySQL
service mysqld restart // 重启数据库方法根据实际情况决定
Shutting down MySQL.. SUCCESS!
Starting MySQL... SUCCESS!
- 3.修改密码
[root@1]# mysql // 以上做完之后,可以直接登录
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.20-log MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
(root@localhost) [(none)]> alter user 'root'@'localhost' identified by '123'; // 这时由于系统检测 skip grant,是不会让你修改密码的。
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
(root@localhost) [(none)]>flush PRIVILEGES; // 再次让密码生效
Query OK, 0 rows affected (0.01 sec)
(root@localhost) [(none)]>alter user 'root'@'localhost' identified by '123'; // 修改密码
Query OK, 0 rows affected (0.00 sec)
(root@localhost) [(none)]>flush tables; // 刷内存数据
Query OK, 0 rows affected (0.00 sec)
(root@localhost) [(none)]>quit // 退出
Bye
- 4.成功现象
[root@1]# mysql // 密码生效,skip grant 失效
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
[root@1]# mysql -uroot -p123 // 这时使用密码登录,就可以正常使用了
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 4
Server version: 5.7.20-log MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
(root@localhost) [(none)]>
注意:记得把配置文件中 skip grant 注释掉