首次登录mysql未设置密码或忘记密码解决方法

  1. 先输入命令:
1
2
3
4
5
6
7
8
9
10
11
12
13
$ sudo cat /etc/mysql/debian.cnf
[sudo] password for katherine:
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host = localhost
user = debian-sys-maint
password = ufBTBJJGhF7a2lyf
socket = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host = localhost
user = debian-sys-maint
password = ufBTBJJGhF7a2lyf
socket = /var/run/mysqld/mysqld.sock
  1. 再输入命令:
1
$ mysql -u debian-sys-maint -p

密码是上条命令中的password内容

  1. 修改密码:
1
2
3
4
5
6
7
8
9
mysql> use mysql;

mysql> update mysql.user set authentication_string=password('your_password') where user='root' and Host ='localhost';

mysql> update user set plugin="mysql_native_password";

mysql> flush privileges;

mysql> quit;
  1. 重新启动mysql
1
2
$ sudo service mysql restart
$ mysql -u root -p

密码策略问题异常信息

ERROR 1819 (HY000):
Your password does not satisfy the current policy requirements.
解决办法:

  1. 查看mysql初始密码策略:
1
mysql> SHOW VARIABLES LIKE 'validate_password%';
  1. 设置密码的验证强度等级,设置 validate_password_policy 的全局参数为 LOW 即可:
1
mysql> set global validate_password_policy=LOW;
  1. 设置为 6 位的密码,设置 validate_password_length 的全局参数为 6 即可:
1
mysql> set global validate_password_length=6;
  1. 修改密码参数
    1. validate_password_length  固定密码的总长度;
    2. validate_password_dictionary_file 指定密码验证的文件路径;
    3. validate_password_mixed_case_count  整个密码中至少要包含大/小写字母的总个数;
    4. validate_password_number_count  整个密码中至少要包含阿拉伯数字的个数;
    5. validate_password_policy 指定密码的强度验证等级,默认为 MEDIUM;
      关于 validate_password_policy 的取值:
      1. 0/LOW:只验证长度;
      2. 1/MEDIUM:验证长度、数字、大小写、特殊字符;
      3. 2/STRONG:验证长度、数字、大小写、特殊字符、字典文件;
    6. validate_password_special_char_count 整个密码中至少要包含特殊字符的个数;
  2. 现在可以为 mysql 设置简单密码了,只要满足密码限制即可:
1
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_password';

每次访问需要加sudo

在Ubuntu18.04上安装MySQL后,发现在普通用户shell下无法使用root用户名登录MySQL。
mysql -u root -p,提示权限问题,命令必须改为sudo mysql -u root -p

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
mysql> use mysql;

mysql> show tables;
+---------------------------+
| Tables_in_mysql |
+---------------------------+
| db |
| ... |
| ... |
| plugin |
| servers |
| user |
+---------------------------+
31 rows in set (0.00 sec)

mysql> mysql> select User, Host, plugin from user;
+------------------+-----------+-----------------------+
| User | Host | plugin |
+------------------+-----------+-----------------------+
| root | localhost | auth_socket |
| mysql.session | localhost | mysql_native_password |
| mysql.sys | localhost | mysql_native_password |
| debian-sys-maint | localhost | mysql_native_password |
+------------------+-----------+-----------------------+
4 rows in set (0.00 sec)

发现MySQL的root用户的plugin被修改了,只有换成mysql_native_password才可以使用密码登录MySQL。
使用下面的命令更改plugin,同时设置MySQL的root访问密码:

1
2
3
mysql> update mysql.user set authentication_string=PASSWORD('your_password'), plugin='mysql_native_password' where user='root';

mysql> flush privileges;

退出后,用普通权限重启mysql,即可使用root用户。