MySQL基础:修改root密码

MySQL基础:修改root密码
如果忘记了root密码的情况下,需要修改root密码可以考虑使用如下方式进行,首先在mysql的设定文件中设定跳过权限认证,然后重启mysql之后重新设定密码,之后再将权限认证跳过的部分去除,之后再此重启即恢复使用新密码

Step 1: 设定权限认证跳过

# grep skip-grant-tables /etc/mysql/mysql.conf.d/mysqld.cnf
# echo "skip-grant-tables" >>/etc/mysql/mysql.conf.d/mysqld.cnf
# grep skip-grant-tables /etc/mysql/mysql.conf.d/mysqld.cnf
skip-grant-tables
#

Step 2: 重启mysql服务并设定新密码

重启mysql服务,此处由于使用的是mysql的官方镜像,所以重启容器即可。

  • 重新设定mysql的新密码
    由于已经设定了权限认证跳过,所以此处无需输入密码,输入mysql -uroot -p之后,密码无需输入,既可以以root身份登入mysql
# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.16-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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.

mysql> select user();
+--------+
| user() |
+--------+
| [email protected]  |
+--------+
1 row in set (0.00 sec)

mysql>
  • 重新设定mysql的root用户的密码
mysql> 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
mysql> update user set authentication_string = password("liumiaocn") where user = "root";
Query OK, 1 row affected, 1 warning (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql>

Step 3: 去除权限跳过设定

# grep skip-grant-tables /etc/mysql/mysql.conf.d/mysqld.cnf
skip-grant-tables
# sed -i s/skip-grant-tables//g /etc/mysql/mysql.conf.d/mysqld.cnf
# grep skip-grant-tables /etc/mysql/mysql.conf.d/mysqld.cnf
# 

Step 4: 重启mysql服务并以新密码登入

重启mysql服务之后,此时再使用空密码试图进入,则会提示如下错误信息。


# mysql -uroot -p
Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
# 

使用新修改的密码liumiaocn则可正确登入了

# mysql -uroot -pliumiaocn
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.16-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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.

mysql>

总结

修改root密码主要是需要将权限认证的部分进行跳过,在这种情况下重设密码,当然root的密码还是妥善保存为好,另外在实际的环境中使用这种方式如同开了一个后门,audit信息也没有得到很好的保存,需要慎重操作。