Mysql 忘记root密码的解决方案

在互联网的时代,密码安全十分重要。为了安全往往不同的服务都会设置不同的密码,不常用的服务密码就有可能忘记。

今天要讲的就是如何在忘记密码的情况下修改Mysql的root密码。

首先确认服务器出于安全的状态,确保别人在你修改密码的时候能连接到你的数据库。因为下面操作修改root密码时,任何人是可以随意连接到你的Mysql服务器的,所以此时你的数据库是没有任何安全可言。

确保服务安全之后,编辑Mysql的配置文件。

1
vi /etc/my.cnf

在[mysqld]段中加上:skip-grant-tables

例如:

1
2
3
4
[mysqld] 
datadir=/var/lib/mysql 
socket=/var/lib/mysql/mysql.sock 
skip-grant-tables

保存并退出vi,然后重启Mysql数据库。

1
2
3
/etc/init.d/mysqld restart 
Stopping MySQL: [ OK ] 
Starting MySQL: [ OK ]

此时登录Mysql数据库的时候是无需密码的,任何人都可以直接登录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/usr/bin/mysql 
Welcome to the MySQL monitor. Commands end with ; or \g. 
Your MySQL connection id is 3 to server version: 3.23.56 
Type 'help;' or '\h' for help. Type '\c' to clear the buffer. 

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 Password = password ( 'new-password' ) WHERE User = 'root' ;
Query OK, 0 rows affected (0.00 sec) 
Rows matched: 2 Changed: 0 Warnings: 0 

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

mysql> quit

上面的“new-password”是你的root新密码,修改完全成后,把之前Mysql配置文件中的skip-grant-tables删除。

然后重启Mysql数据库。用刚设置的root密码登录。