mysql忘记了root密码(亲测有效)

Mysql8.0以上重置初始密码的方法1

修改密码的强度等级:参考
1.修改配置文件my.cnf,在配置文件[mysqld]下添加skip-grant-tables,重启MySQL服务即可免密码登录
  其中–skip-grant-tables 选项前面曾经介绍过,意思是启动 MySQL 服务的时候跳过权限表认证。 启动后,连接到 MySQL 的 root 将不需要口令。

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
[mysqld]

skip-grant-tables

2.用空密码的 root 用户连接到 MySQL,并且更改 root 口令:

[root@localhost mysql]# mysql -uroot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 53
Server version: 5.0.41-community-log MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123';  
 ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement


mysql> update user set authentication_string = NULL where user = 'root';
Query OK, 1 row affected (0.00 sec)

上面是先用grant的方式修改root密码,但是由于使用了配置了skip-grant-tables 选项,使用“alter user”命令更改密码失败,直

接更新 user 表的 authentication_string字段后更改密码成功。
3.到my.cnf 中删除skip-grant-tables选项,然后直接用mysql -uroot免密码登录后,在执行如下语句重设密码

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123';  

4.重新用 root 登录时,必须输入新口令。

更优雅的解法

相对于skip-grant-tables方案,我们来看看另外一种更优雅的解法,其只会重启一次,且基本上不存在安全隐患。

首先,依旧是关闭实例

其次,创建一个sql文件

写上密码修改语句

# vim init.sql 
alter user 'root'@'localhost' identified by '123456';

最后,使用–init-file参数,启动实例

# bin/mysqld_safe --defaults-file=my.cnf --init-file=/usr/local/mysql57/init.sql &

实例启动成功后,密码即修改完毕~

如果mysql实例是通过服务脚本来管理的,除了创建sql文件,整个操作可简化为一步。

# service mysqld restart --init-file=/usr/local/mysql57/init.sql 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值