浅谈Mysql连接数据库时host和user的匹配规则

--连接数据库时,host和user的匹配规则

官方文档:https://dev.mysql.com/doc/refman/5.7/en/connection-access.html

--host和user的匹配规则如下:

--是host为明确的最先匹配,host带%模糊的时候最后匹配,但host为''(空)位于%之后才匹配

--相同的host时候,比较user为明确的最先匹配,user为''(空)最后匹配

--相同的host和user时,排序是不确定的

When multiple matches are possible, the server must determine which of them to use. It resolves this issue as follows:
Whenever the server reads the user table into memory, it sorts the rows.
When a client attempts to connect, the server looks through the rows in sorted order.
The server uses the first row that matches the client host name and user name.
The server uses sorting rules that order rows with the most-specific Host values first. Literal host names and IP addresses are the most specific. (The specificity of a literal IP address is not affected by whether it has a netmask, so 198.51.100.13 and 198.51.100.0/255.255.255.0 are considered equally specific.) The pattern '%' means “any host” and is least specific. The empty string '' also means “any host” but sorts after '%'. Rows with the same Host value are ordered with the most-specific User values first (a blank User value means “any user” and is least specific). For rows with equally-specific Host and User values, the order is nondeterministic.

--查看当前的host及用户信息匹配顺序,先host顺序匹配、后user顺序匹配

mysql> SELECT authentication_string, host, user,account_locked FROM mysql.USER ORDER BY host desc ,user desc;
+-------------------------------------------+--------------+---------------+----------------+
| authentication_string      | host   | user   | account_locked |
+-------------------------------------------+--------------+---------------+----------------+
| *511C0A408C5065XXEC90D60YYA1AB9437281AF28 | localhost | root   | N    |
| *THISISNOTAVALIXXASSWORDYYATCANBEUSEDHERE | localhost | mysql.sys  | Y    |
| *THISISNOTAVALIXXASSWORDYYATCANBEUSEDHERE | localhost | mysql.session | Y    |
| *485CE31BA547A4XXC047659YY10DF200F361CD4E | localhost | bkpuser  | N    |
| *7B502777D8FF69XX4B56BC2YY2867F4B47321BA8 | 192.168.56.% | repl   | N    |
| *AECCE73463829AXX3968838YYF6F85E43C3F169C | %   | flyremote  | N    |
| *566AC8467DAAAEXXE247AE7YY0A770E9B97D9FB0 |    | flylocal  | N    |
+-------------------------------------------+--------------+---------------+----------------+
8 rows in set (0.00 sec)
 

--举个特殊例子

--建立两个特殊用户如下,一个用户名为''(空)、一个用户名和host都为''(空)

mysql> create user ''@'localhost' identified by "Kong123$";
Query OK, 0 rows affected (0.00 sec)
mysql> create user ''@'' identified by "doubleKong123$";
Query OK, 0 rows affected (0.00 sec)

--查看当前的host及用户信息匹配顺序,先host顺序匹配、后user顺序匹配

mysql> SELECT authentication_string, host, user,account_locked FROM mysql.USER ORDER BY host desc ,user desc;
+-------------------------------------------+--------------+---------------+----------------+
| authentication_string      | host   | user   | account_locked |
+-------------------------------------------+--------------+---------------+----------------+
| *511C0VVV8C5065CBEC90D6TTTT1AB9437281AF28 | localhost | root   | N    |
| *THISIVVVTAVALIDPASSWORTTTTTCANBEUSEDHERE | localhost | mysql.sys  | Y    |
| *THISIVVVTAVALIDPASSWORTTTTTCANBEUSEDHERE | localhost | mysql.session | Y    |
| *485CEVVVA547A48CC04765TTTT0DF200F361CD4E | localhost | bkpuser  | N    |
| *256D7VVV91F7363EBDADEFTTTTB74B2B318746FC | localhost |    | N    |
| *7B502VVVD8FF69164B56BCTTTT867F4B47321BA8 | 192.168.56.% | repl   | N    |
| *AECCEVVV63829A5F396883TTTT6F85E43C3F169C | %   | flyremote  | N    |
| *566ACVVV7DAAAE79E247AETTTTA770E9B97D9FB0 |    | flylocal  | N    |
| *AE162VVV68403D1D98A4C9TTTT50A508B8C56F3F |    |    | N    |
+-------------------------------------------+--------------+---------------+----------------+
9 rows in set (0.00 sec)

--这样本地登录flyremote用户时 会报错,因为按以上的顺序 优先匹配到了host为localhost、user为''(空)的用户,而不是flyremote用户 (因为user为''(空)的用户可以匹配任意用户名)

[root@hostmysql-m mysql]# mysql -uflyremote -pFlyremote123$
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'flyremote'@'localhost' (using password: YES)

--那就是说本地登录flyremote用户时, 用匹配到的host为localhost、user为''(空)的密码 Kong123$ ,就可以正常登陆了

[root@hostmysql-m mysql]# mysql -uflyremote -pKong123$
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 15
Server version: 5.7.23-log 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> select user(),CURRENT_USER();
+---------------------+----------------+
| user()    | CURRENT_USER() |
+---------------------+----------------+
| flyremote@localhost | @localhost  |
+---------------------+----------------+
1 row in set (0.06 sec)

--用带入ip的方式登录flyremote用户时 无问题, ip匹配到了% ,user匹配到了flyremote

[root@hostmysql-m mysql]# mysql -uflyremote -pFlyremote123$ -h127.11.22.33
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 12
Server version: 5.7.23-log 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> select user(),CURRENT_USER();
+------------------------+----------------+
| user()     | CURRENT_USER() |
+------------------------+----------------+
| flyremote@127.11.22.33 | flyremote@% |
+------------------------+----------------+
1 row in set (0.00 sec)

--任意用户、任意host,只要密码和建立的第二个空用户空host的密码"doubleKong123$"匹配了, 就可以进入mysql

--测试一个不存在的用户hahaha

[root@hostmysql-m ~]# mysql -uhahaha -pdoubleKong123$ -h127.11.22.33
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 6
Server version: 5.7.23-log 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> select user(),CURRENT_USER();
+---------------------+----------------+
| user()    | CURRENT_USER() |
+---------------------+----------------+
| hahaha@127.11.22.33 | @    |
+---------------------+----------------+
1 row in set (0.01 sec)

--解决方案:

1、手工删除空用户和空host用户确保安全

或者

2、使用 mysql_secure_installation 来进行安全配置

--安全配置如下,其中有删除匿名用户的操作

This program enables you to improve the security of your MySQL installation in the following ways:
 You can set a password for root accounts.
 You can remove root accounts that are accessible from outside the local host.
 You can remove anonymous-user accounts.
 You can remove the test database (which by default can be accessed by all users, even anonymous users), and privileges that permit anyone to access databases with names that start with test_.

--删除匿名用户的源码 mysql_secure_installation.cc 如下:

 //Remove anonymous users
 remove_anonymous_users();
/**
 Removes all the anonymous users for better security.
*/
void remove_anonymous_users()
{
 int reply;
 reply= get_response((const char *) "By default, a MySQL installation has an "
      "anonymous user,\nallowing anyone to log "
      "into MySQL without having to have\na user "
      "account created for them. This is intended "
      "only for\ntesting, and to make the "
      "installation go a bit smoother.\nYou should "
      "remove them before moving into a production\n"
      "environment.\n\nRemove anonymous users? "
      "(Press y|Y for Yes, any other key for No) : ", 'y');

 if (reply == (int) 'y' || reply == (int) 'Y')
 {
 const char *query;
 query= "SELECT USER, HOST FROM mysql.user WHERE USER=''";
 if (!execute_query(&query, strlen(query)))
  DBUG_PRINT("info", ("query success!"));
 MYSQL_RES *result= mysql_store_result(&mysql);
 if (result)
  drop_users(result);
 mysql_free_result(result);
 fprintf(stdout, "Success.\n\n");
 }
 else
 fprintf(stdout, "\n ... skipping.\n\n");
}

补充:mysql 用户表中多个host时的匹配规则

mysql数据库中user表的host字段,是用来控制用户访问数据库“权限”的。

可以使用“%”,表示所有的网段;

也可以使用具体的ip地址,表示只有该ip的客户端才可以登录到mysql服务器;

也可以使用“_”进行模糊匹配,表示某个网段的客户端可以登录到mysql服务器。

如果在user表中存在一个用户两条不同host值的记录,那么mysql服务器该如何匹配该用户的权限呢?

mysql采用的策略是:当服务器读取user表时,它首先以最具体的Host值排序(主机名和IP号是最具体的) 。有相同Host值的条目首先以最具体的User匹配。

举例:

如下,有两条root用户,那么只有localhost的root客户端可以登录到mysql服务器。

| root | localhost | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| root | %   | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • 如何快速修改MySQL用户的host属性

    当你远程登录MySQL时,使用的账号要有特殊要求. 默认的账号的host属性都是localhost,意思是这个账号只能本地使用,如果要使用某个账号来远程登录,必须将账号的host属性值更改成%. 执行的sql语句如下: update user set host = '%' where user = 'root'; 补充:mysql 修改root密码 修改账户登录host 1.忘了root密码 远程服务器起了一个mysql服务,里面有个hive账户,在远程服务器能通过命令行用mysql -hloc

  • MySQL新建用户中的%到底包不包括localhost?

    正常解释 %代表任何客户机都可以连接 localhost代表只可以本机连接 一般情况能访问本地数据库的都是加了权限了,一般都是禁止别的机器访问本地的mysql端口的,如果允许也是要加上指定ip才可以访问,这样才能保证数据库不会被远程访问. 1 前言 操作MySQL的时候发现,有时只建了%的账号,可以通过localhost连接,有时候却不可以,网上搜索也找不到满意的答案,干脆手动测试一波 2 两种连接方法 这里说的两种连接方法指是执行mysql命令时,-h参数填的是localhost还是IP, 两

  • mysql允许所有host访问的方法

    1. 把mysql库中user表中的一条记录的Host字段值改为 %, 奇怪的是一定要用以下语句设置一下密码才行 2. update user set Password=PASSWORD("123456") WHERE  Host="%"; 3. 执行 flush privileges 命令使立即生效 以上这篇mysql允许所有host访问的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • MySQL 可以用localhost 连接,但不能用IP连接的问题解决方法

    MySQL localhost 连接,但不能用IP连接问题解决方案 主要涉及到MySQL 可以用localhost 连接,但不能用IP连接的问题 方面的内容,对于MySQL 可以用localhost 连接,但不能用IP连接的问题 1.打开cmd窗口,进入MySQL安装的bin目录 2.执行命令登录数据库,之后会出现一行要你输入密码的 mysql -u root -p 3.执行以下命令分配新用户: grant all privileges on *.* to 'root'@'%' identifi

  • 完美解决MySQL通过localhost无法连接数据库的问题

    问题:一台服务器的PHP程序通过localhost地址无法连接数据库,但是如果设置为127.0.0.1则可以正常连接,连接其他数据库服务器也正常.MySQL的权限设置正确,且通过mysql命令行客户端可以正常连接数据库. 分析:这是典型的socket没有正确设置的情况. 连接MySQL数据库有两种方式:TCP/IP(一般理解的端口的那种)和Unix套接字(一般叫socket或者sock).大部分情况下,可以用localhost代表本机127.0.0.1,但是在MySQL连接时,二者不可混用,而且

  • 浅谈Mysql连接数据库时host和user的匹配规则

    --连接数据库时,host和user的匹配规则 官方文档:https://dev.mysql.com/doc/refman/5.7/en/connection-access.html --host和user的匹配规则如下: --是host为明确的最先匹配,host带%模糊的时候最后匹配,但host为''(空)位于%之后才匹配 --相同的host时候,比较user为明确的最先匹配,user为''(空)最后匹配 --相同的host和user时,排序是不确定的 When multiple matche

  • 浅谈mysql 针对单张表的备份与还原

    A.MySQL 备份工具xtrabackup 的安装 1. percona 官方xtrabackup 的二进制版本:二进制版本解压就能用了. 2. 解压xtrabackup & 创建连接 tar -xzvf percona-xtrabackup-2.3.4-Linux-x86_64.tar.gz -C /usr/local/ ln -s /usr/local/percona-xtrabackup-2.3.4 /usr/local/xtrabackup 3. 设置PATH环境变量 export P

  • 浅谈mysql密码遗忘和登陆报错的问题

    mysql登录密码忘记,其实解决办法很简单,只需要在mysql的主配置文件my.cnf里添加一行"跳过授权表"的参数选择即可! 在my.cnf中添加下面一行: [root@test-huanqiu ~]# vim /etc/my.cnf              //在[mysqld]区域里添加 ........ skip-grant-tables                       //跳过授权表 然后重启mysql服务,即可无密码登录 [root@test-huanqiu

  • 浅谈MySQL中授权(grant)和撤销授权(revoke)用法详解

    MySQL 赋予用户权限命令的简单格式可概括为: grant 权限 on 数据库对象 to 用户 一.grant 普通数据用户,查询.插入.更新.删除 数据库中所有表数据的权利 grant select on testdb.* to common_user@'%' grant insert on testdb.* to common_user@'%' grant update on testdb.* to common_user@'%' grant delete on testdb.* to c

  • 浅谈MySQL在cmd和python下的常用操作

    环境配置1:安装mysql,环境变量添加mysql的bin目录 环境配置2:python安装MySQL-Python 请根据自身操作系统下载安装,否则会报c ++ compile 9.0,import _mysql等错误 windows10 64位操作系统可到 http://www.lfd.uci.edu/~gohlke/pythonlibs/ 下载安装MySQL-Python包,至于whl和tar.gz在windows和Linux下的安装方法可查看我的上一篇文章 一 .cmd命令下的操作: 连

  • 浅谈MySQL user权限表

    MySQL 在安装时会自动创建一个名为 mysql 的数据库,mysql 数据库中存储的都是用户权限表.用户登录以后,MySQL 会根据这些权限表的内容为每个用户赋予相应的权限. user 表是 MySQL 中最重要的一个权限表,用来记录允许连接到服务器的账号信息.需要注意的是,在 user 表里启用的所有权限都是全局级的,适用于所有数据库. user 表中的字段大致可以分为 4 类,分别是用户列.权限列.安全列和资源控制列,下面主要介绍这些字段的含义. 用户列 用户列存储了用户连接 MySQL

  • 浅谈MySQL数据查询太多会OOM吗

    目录 全表扫描对server层的影响 全表扫描对InnoDB的影响 InnoDB内存管理 小结 我的主机内存只有100G,现在要全表扫描一个200G大表,会不会把DB主机的内存用光? 逻辑备份时,可不就是做整库扫描吗?若这样就会把内存吃光,逻辑备份不是早就挂了? 所以大表全表扫描,看起来应该没问题.这是为啥呢? 全表扫描对server层的影响 假设,我们现在要对一个200G的InnoDB表db1. t,执行一个全表扫描.当然,你要把扫描结果保存在客户端,会使用类似这样的命令: mysql -h$

  • 浅谈MySQL和Lucene索引的对比分析

    MySQL和Lucene都可以对数据构建索引并通过索引查询数据,一个是关系型数据库,一个是构建搜索引擎(Solr.ElasticSearch)的核心类库.两者的索引(index)有什么区别呢?以前写过一篇<Solr与MySQL查询性能对比>,只是简单的对比了下查询性能,对于内部原理却没有解释,本文简单分析下两者的索引区别. MySQL索引实现 在MySQL中,索引属于存储引擎级别的概念,不同存储引擎对索引的实现方式是不同的,本文主要讨论MyISAM和InnoDB两个存储引擎的索引实现方式. M

  • 浅谈mysql中多表不关联查询的实现方法

    大家在使用MySQL查询时正常是直接一个表的查询,要不然也就是多表的关联查询,使用到了左联结(left join).右联结(right join).内联结(inner join).外联结(outer join).这种都是两个表之间有一定关联,也就是我们常常说的有一个外键对应关系,可以使用到 a.id = b.aId这种语句去写的关系了.这种是大家常常使用的,可是有时候我们会需要去同时查询两个或者是多个表的时候,这些表又是没有互相关联的,比如要查user表和user_history表中的某一些数据

  • 浅谈mysql的子查询联合与in的效率

    最近的产品测试发现一个问题,当并发数量小于10时,响应时间可以维持在100毫秒以内.但是当并发数到达30个时,响应时间就超过1秒.这太不能接受了,要求是通过1秒中并发100个. 经过检测发现,时间主要是耗在其中的一个存储过程中.把存储过程的语句一条一条的过一遍也没有发现明显的不合理.因为mysql本身不能提供毫秒级别的时间,google了一个mysql的能提供毫秒的时间函数,再做测试,做了一个定位.发现是其中一条语句,语句是这个样子: select .... from A, B where ..

随机推荐