找到my.cnf文件并使用vim修改文件
vim /etc/my.cnf
在最后添加skip-grant-tables并重启查看mysql状态
#停止mysql
systemctl stop mysqld
#修改完毕后启动mysql
systemctl start mysqld
#并查看下状态,如果Active为actvie(running)即为启动成功
systemctl status mysqld
操作到这一步即可跳过密码登录mysql,而后切换数据库
#切换数据库
use mysql;
#切换完毕后修改密码
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的新密码'
#如果修改失败刷新一下mysql权限即可
flush privileges;
#刷新完毕再次尝试
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的新密码'
#修改完毕后推出数据库
exit
这里的'root'@'localhost' 是指定为仅当前主机可以登录
记得删除开始配置的skip-grant-tables,然后重新启动mysql即可