数据库新建用户后(Host:%),报错:localhost无法连接

存在问题

在给数据库(MySQL、MariaDB等)创建了新的用户名(eg:maxscale)后,无法使用新用户名登录,并报如下错误:ERROR 1045 (28000): Access denied for user 'maxscale'@'localhost' (using password: YES)

相信遇到该问题的人都有这样的疑问:明明创建用户时,host为‘%’,正常情况下所有的主机应该都可以连接呀,为什么报错'localhost'无法连接?

解决方案及问题分析,如下!

查看用户表

MariaDB [(none)]> select user,host from mysql.user;
+-------------+----------------+
| User        | Host           |
+-------------+----------------+
|             | localhost      |
| mariadb.sys | localhost      |
| mariadb10   | localhost      |
| root        | localhost      |
|             | vm172-0-11-157 |
+-------------+----------------+

创建用户

-- 创建用户
create user maxscale@'%' identified by "123456";
grant replication client, replication slave, select on *.* to maxscale@'%';

-- 查看用户
MariaDB [(none)]> select user,host from mysql.user;
+-------------+----------------+
| User        | Host           |
+-------------+----------------+
| maxscale    | %              |
|             | localhost      |
| mariadb.sys | localhost      |
| mariadb10   | localhost      |
| root        | localhost      |
|             | vm172-0-11-157 |
+-------------+----------------+
9 rows in set (0.003 sec)

连接数据库

在已经启动数据库的前提下,连接数据库:

/home/mariadb10/node5307/mysql/bin/mysql --defaults-file=/home/mariadb10/node5307/my.cnf -h127.0.0.1 -umaxscale -p123456 -P5307

连接报错:

原因分析

上述连接命令使用127.0.0.1作为主机名,MariaDB在mysql.user表中首先查找Host为127.0.0.1的用户条目,如果没有找到,它会查找Host为localhost的用户条目。由于maxscale用户对应的Host是%,理论上应该能够匹配任何主机,包括127.0.0.1和localhost。

但是,如果MariaDB在处理连接请求时,由于某些原因(可能是配置问题或权限问题)没有正确识别maxscale@%用户,它可能会退回到使用匿名用户。

解决办法

删除匿名用户!

1)查找匿名用户

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE User = '';
+------+----------------+
| User | Host           |
+------+----------------+
|      | localhost      |
|      | vm172-0-11-157 |
+------+----------------+
2 rows in set (0.001 sec)

2)删除匿名用户

MariaDB [(none)]> drop user ''@'localhost';
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE User = '';
+------+----------------+
| User | Host           |
+------+----------------+
|      | vm172-0-11-157 |
+------+----------------+
1 row in set (0.001 sec)

3)重新连接数据库

注意:匿名用户权限很高,非必要情况下,优选删除匿名用户!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据库内核

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值