需求:某个用户指定ip机器能访问数据库
root@(none) 09:57:51>GRANT SELECT, RELOAD, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'jingwei'@'ip1,ip2' IDENTIFIED BY '*****';
Query OK, 0 rows affected, 1 warning (0.00 sec)
直接授权用逗号隔开发现warning:
root@(none) 09:57:52>show warnings\G
*************************** 1. row ***************************
Level: Warning
Code: 1285
Message: MySQL is started in --skip-name-resolve mode; you must restart it without this switch for this grant to work
1 row in set (0.00 sec)
删掉用户重新授权遇到报错:
root@(none) 09:57:58>drop user jingwei;
ERROR 1396 (HY000): Operation DROP USER failed for 'jingwei'@'%'
root@(none) 10:07:21>show grants for jingwei;
ERROR 1141 (42000): There is no such grant defined for user 'jingwei' on host '%'
用户存在,但不是@'%' 直接drop用户会默认@'%'所以执行不成功,将mysql.user表中的user信息查询出来即可知道上面的授权语句是执行成功了写入了ip1,ip2两个ip填充了host,根据host可将该用户删除:
root@(none) 10:10:19>delete from mysql.userwhere host='ip1,ip2';
Query OK, 1 row affected (0.00 sec)
或者删除的时候用“用户@'ip1,ip2':
root@(none) 11:25:45>drop user jingwei@'ip1,ip2';
Query OK, 0 rows affected (0.00 sec)
同样的查看授权也可以用“用户@'ip1,ip2':
root@(none) 11:28:30>show grants for jingwei@'ip1,ip2';
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for jingwei@ip1,ip2 |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, RELOAD, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'jingwei'@'ip1,ip2' IDENTIFIED BY PASSWORD '****' |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
正确的授权:
GRANT SELECT, RELOAD, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'jingwei'@'ip1' IDENTIFIED BY '*****';
GRANT SELECT, RELOAD, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'jingwei'@'ip2' IDENTIFIED BY '*****';
每个ip逐一授权的好处在于要回收某台机器的权限时可方便的执行
另外一种授权方式可以在ip之间用'/'进行分割,但是在revoke权限时必须全部一起回收:
GRANT SELECT, RELOAD, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'jingwei'@'ip1/ip2' IDENTIFIED BY '*****';
revoke SELECT, RELOAD, REPLICATION SLAVE, REPLICATION CLIENT ON *.* from 'jingwei'@'ip1/ip2';
建议白名单控制还是逐条执行授权!