1、检查mysql服务是否启动,如果启动,关闭mysql服务
[root@iZuf6931vw5cx71wacor0eZ ~]# ps -ef | grep -i mysql
root 6084 5890 0 15:20 pts/0 00:00:00 grep --color=auto -i mysql
[root@iZuf6931vw5cx71wacor0eZ ~]# service mysql stop
Redirecting to /bin/systemctl stop mysql.service
2、修改mysql的配置文件my.cnf
# my.cnf配置文件的位置,一般在/etc/my.cnf,有些版本在/etc/mysql/my.cnf
[root@iZuf6931vw5cx71wacor0eZ ~]#vim /etc/my.cnf
# 在第2行添加代码
skip-grant-tables
3、启动mysql
[root@iZuf6931vw5cx71wacor0eZ ~]# service mysqld start
4、免密进入mysql
[root@iZuf6931vw5cx71wacor0eZ ~]# mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 8.0.16 MySQL Community Server - GPL
mysql>
5、修改密码
mysql> update mysql.user set authentication_string=password('新密码') where user='root';
注意:
如果以下报错误:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('******') where user='root'' at line 1
1、查询初始密码
[root@iZuf6931vw5cx71wacor0eZ ~]# grep 'temporary password' /var/log/mysqld.log
2019-06-15T08:36:29.457981Z 5 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: M=w?c*#.I7ve
2、注释掉刚才在mysql的配置文件my.cnf中 添加的skip-grant-tables
3、利用初始密码登录mysql 并修改密码
[root@iZuf6931vw5cx71wacor0eZ etc]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.16 MySQL Community Server - GPL
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY '复杂的新密码';