1 、故障描述
某次某用户,一套 MySQL 环境,使用 teg 用户登录时,输入密码报错,密码置空,却可以登录,具体现象如下:
输入密码报错
mysql -uteg -p123
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'teg'@'localhost' (using password: YES)
密码置空,登录成功
mysql -uteg -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 353
Server version: 5.7.44-log MySQL Community Server (GPL)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
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.
2 、根因分析
( 1 )、尝试重置密码
alter user teg@'%' identified by '123';
再次登录,问题依然存在
mysql -uteg -p123
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'teg'@'localhost' (using password: YES)
( 2 )、确认 host 为 localhost 的 teg 用户
SELECT User, Host, plugin, authentication_string FROM mysql.user WHERE User='teg';

根据输出,可以明确 MySQL 中仅存在 teg@'%' 一个用户,且密码不为空。
( 3 )、尝试指定 IP 地址登录
Mysql -h192.168.254.23 -uteg -p123
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'teg'@'%' (using password: YES)
根据输出,可以明确指定 ip 也无法正常登录。
( 4 )、确认 host 为 localhost 的匿名用户
SELECT user, host, plugin,authentication_string FROM mysql.user WHERE user = '';

根据输出,确实存在符合条件的匿名用户。
在 MySQL 中,如果存在匿名用户,且我们使用一个不存在的用户名(在 localhost 上)进行连接,那么可能会使用匿名用户。但是,在连接命令中指定了用户名 teg ,所以 MySQL 会尝试匹配 teg@'localhost' ,如果不存在,则连接失败。然而,这里不带密码能登录,说明匹配到了一个不需要密码的用户。
因此,我们怀疑存在一个匿名用户( ''@'localhost' )且没有密码,同时允许通过 socket 连接。当我们使用 mysql -uteg 时,实际上是以匿名用户登录了,但是 MySQL 客户端显示的是我们指定的用户名(尽管在服务器端实际是匿名用户)。这可以解释为什么不需要密码。
3 、解决方案
尝试先删除匿名用户
drop user ''@'localhost';
Query OK, 0 rows affected (0.07 sec)
再进行登录尝试,正常
mysql -uteg -p123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 353
Server version: 5.7.44-log MySQL Community Server (GPL)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
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.
