MySQL如何设置白名单?

1、首先看下有登陆权限的机器

use mysql;
select Host,User from user;
+-----------+---------------+
| Host | User |
+-----------+---------------+
| % | root |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+---------------+
4 rows in set (0.00 sec)

2、指定单个IP可以登陆

GRANT ALL ON . to root@'192.168.192.134' IDENTIFIED BY '密码';

注意:MySQL通配符是用 %,不是 *

3、制定一个网段可以登录

在ip里指定1个或多个通配符,需要加上 WITH GRANT OPTION 参数,否则会不生效,具体官方文档有解释,看文末。

GRANT ALL PRIVILEGES ON . TO root@'192.168.192.%' IDENTIFIED BY 'root' WITH GRANT OPTION;

GRANT ALL PRIVILEGES ON . TO root@'192.168.%.%' IDENTIFIED BY 'root' WITH GRANT OPTION;

4、去除所有节点登陆权限

如果Host里是%,就代表任意节点都可以访问登陆,删除host是%的这行,就能实现仅指定ip白名单登录的目的。

DELETE FROM user WHERE User='root' and Host='%';

5、刷新使得修改的权限生效

FLUSH PRIVILEGES;

6、验证

mysql> select host,user from user;
+-----------------+---------------+
| host | user |
+-----------------+---------------+
| 192.168.192.% | root |
| 192.168.192.134 | root |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------------+---------------+
5 rows in set (0.00 sec)

授权节点登录正常授权用户,未授权节点登录异常,未授权用户。

7、官网关于 GRANT OPTION 参数的介绍

https://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html

GRANT OPTION参数:允许用户将自己的权限授予其他用户,两个拥有不同权限且具有GRANT OPTION权限的用户可以组合权限。

本文由《MySql教程网》原创,转载请注明出处!https://mysql360.com