筆者在CentOS7上安裝MySQL 5.7版本,安裝完成後,登錄的時候,提示登錄被拒絕:
[root@cdh1 ~]# mysql -uroot -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
以前安裝5.6版本的時候,root用戶的默認密碼爲空, 提示輸入密碼時,敲回車即能登錄。但是此次安裝的5.7版本按默認密碼爲空的方式登錄,卻不能登錄。原因是5.7版本中,系統會隨機爲root用戶設置一個密碼。此時,若想進入mysql命令行模式,需先進行root用戶的密碼重置操作。
root用戶密碼重置非常簡單:
1、修改文件:/etc/my.cnf :
找到 mysql配置的代碼塊,添加一行配置 skip-grant-tables , 繞過密碼驗證,如下圖:
修改完,保存退出,並重啓mysql
[root@cdh1 etc]# systemctl restart mysqld.service
2、進入mysql命令行, 修改root用戶的密碼:
[root@cdh1 etc]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.21 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
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 authentication_string = password('123'), password_expired = 'N', password_last_changed = now() where user = 'root';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 1
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit;
Bye
此處需要注意,在5.6版本中,密碼字段是 password , 在5.7版本中,密碼字段是 authentication_string 。
3、將/etc/my.cnf 文件恢復原狀,即刪除第一步中添加的配置:skip-grant-tables , 保存退出。
4、重啓mysql服務,即可使用新密碼進行登錄:
[root@cdh1 etc]# systemctl restart mysqld.service
[root@cdh1 etc]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.21 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
至此,MySQL 的root用戶默認密碼修改完成!