存在問題
在給數據庫(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)重新連接數據庫
注意:匿名用戶權限很高,非必要情況下,優選刪除匿名用戶!