MySQL数据库忘记登陆密码

一、数据库连接原理

 

第一步,你会先连接到这个数据库上,这时候接待你的就是连接器。连接器负责跟客户端建⽴连接、获取权限、维持和管理连接。连接命令一般是这么写的:

mysql -h$ip -P$port -u$user -p

输完命令之后,你就需要在交互对话里边输入密码。虽然密码也可以直接跟在-p后面写在命令中,但这样可能会导致你的密码泄露。如果你连的是生产服务器,强烈建议你不要这么做。
连接命令中的mysql是客户端工具,用来跟服务端建立连接。在完成经典的TCP握手后,连接器就要开始认证你的身份,这个时候用的就是你输入的用户名和密码。

  • 如果用户名或密码不对,你就会收到一个"Access denied for user"的错误,然后客户端程序结束执行。
  • 如果用户名密码认证通过,连接器会到权限表里面查出你拥有的权限。之后,这个连接里面的权限判断逻辑,都将依赖于此时读到的权限。

这就意味着,一个用户成功建立连接后,即使你用管理员账号对这个用户的权限做了修改,也不会影响已经存在连接的权限。修改完成后,只有再新建的连接才会使用新的权限设置。

连接完成后,如果你没有后续的动作,这个连接就处于空闲状态,你可以在show processlist命令中看到它。文本中这个图是show processlist的结果,其中的Command列显示为“Sleep”的这一行,就表示现在系统里面有一个空闲连接。

二、重置密码数据库处于关闭状态

[root@mysql ~]# ps -ef | grep mysqld
root       2210   1729  0 20:11 pts/0    00:00:00 grep --color=auto mysqld

三、重启数据库跳过授权

[root@mysql mysql3306]# /mysql3306/bin/mysqld --defaults-file=/mysql3306/my.cnf --skip-grant-tables --skip-networking=on --user=mysql &

四、直接登陆数据库

提示输入密码,直接回车

[root@mysql mysql3306]# 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.26 MySQL Community Server (GPL)

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

登陆后刷新权限

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

五、修改密码

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

六、修改完成后结束任务

mysql> exit
Bye
[root@mysql mysql3306]# jobs
[1]+  Running                 /mysql3306/bin/mysqld --defaults-file=/mysql3306/my.cnf --skip-grant-tables --skip-networking=on --user=mysql &
[root@mysql mysql3306]# 
[root@mysql mysql3306]# kill %1

七、使用新密码登陆

[root@mysql mysql3306]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.26 MySQL Community Server (GPL)

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

 

posted @ 2023-12-24 09:34  中仕  阅读(15)  评论(0编辑  收藏  举报