如何在 MySQL 8.0 中重置 root 密码
如果不幸忘记或丢失 MySQL root 密码,您肯定需要一种方法来恢复它。我们需要知道的是密码存储在users表中。这意味着我们需要想办法绕过MySQL身份验证,这样我们就可以更新密码记录。
幸运的是,有一个很容易实现的方法,本教程将指导您完成在 MySQL 8.0 版本中恢复或重置 root 密码的过程。
根据 MySQL 文档,有两种方法可以重置 MySQL root 密码。我们将对两者进行审查。
使用 –init-file 重置 MySQL Root 密码
重置 root 密码的方法之一是创建本地文件,然后使用 --init-file
选项启动 MySQL 服务,如下所示。
vim /home/user/init-file.txt
确保 mysql 用户可以读取该文件非常重要。在该文件中粘贴以下内容:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
在上面的内容中,将“new_password”更改为您要使用的密码。
现在确保 MySQL 服务已停止。您可以执行以下操作:
systemctl stop mysqld.service # for distros using systemd
/etc/init.d/mysqld stop # for distros using init
然后运行以下命令:
mysqld --user=mysql --init-file=/home/user/init-file.txt --console
这将启动 MySQL 服务,在此过程中它将执行您创建的 init 文件,从而更新 root 用户的密码。重置密码后,请务必删除该文件。
确保停止服务器并随后正常启动。
systemctl stop mysqld.service # for distros using systemd
systemctl restart mysqld.service # for distros using systemd
/etc/init.d/mysqld stop # for distros using init
/etc/init.d/mysqld restart # for distros using init
您现在应该能够使用新密码以 root 身份连接到 MySQL 服务器。
mysql -u root -p
使用 –skip-grant-tables 重置 MySQL Root 密码
我们的第二个选项是使用 --skip-grant-tables
选项启动 MySQL 服务。这不太安全,因为当以这种方式启动服务时,所有用户都可以在没有密码的情况下进行连接。
如果服务器启动--skip-grant-tables
,--skip-networking
选项会自动激活,因此远程连接将不可用。
首先确保MySQL服务已停止。
systemctl stop mysqld.service # for distros using systemd
/etc/init.d/mysqld stop # for distros using init
然后使用以下选项启动服务。
mysqld --skip-grant-tables --user=mysql &
然后,只需运行即可连接到mysql服务器。
mysql
由于使用 --skip-grant-tables
选项启动服务时帐户管理被禁用,因此我们必须重新加载授权。这样我们稍后就可以更改密码:
FLUSH PRIVILEGES;
现在您可以运行以下查询来更新密码。确保将“new_password”更改为您要使用的实际密码。
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_passowrd';
现在停止 MySQL 服务器并正常启动。
systemctl stop mysqld.service # for distros using systemd
systemctl restart mysqld.service # for distros using systemd
/etc/init.d/mysqld stop # for distros using init
/etc/init.d/mysqld restart # for distros using init
您应该能够使用新密码进行连接。
mysql -u root -p
您可能还想阅读以下这些有用的 MySQL 相关文章。
- 如何在 CentOS、RHEL 和 Fedora 中安装 MySQL 8
- 15 个有用的 MySQL 性能调优和优化技巧
- Linux 下的 12 个 MySQL 安全实践
- 4 个有用的命令行工具来监控 MySQL 性能
- MySQL 数据库管理启动命令
结论
在本文中,您学习了如何重置 MySQL 8.0 服务器丢失的 root 密码。我希望这个过程很简单。