我可以轻松使用以下代码授予一个IP访问权限:
$ mysql -u root -p
Enter password:
mysql> use mysql
mysql> GRANT ALL ON *.* to root@'192.168.1.4' IDENTIFIED BY 'your-root-password';
mysql> FLUSH PRIVILEGES;
但我需要允许整个子网192.168.1.* 远程访问数据库。
我该如何做到?
看起来你也可以使用网络掩码,例如这里。
GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...
编辑:考虑查看并支持Malvineous在该页面上的答案。掩码是一种更加优雅的解决方案。
在IP地址中使用百分号作为通配符即可。
来自http://dev.mysql.com/doc/refman/5.1/en/grant.html
您可以在主机名中指定通配符。例如,
user_name@'%.example.com'
适用于example.com
域中任何主机的user_name
,而user_name@'192.168.1.%'
适用于192.168.1
类C子网中任何主机的user_name
。
你可以像这样使用“%”作为通配符:
GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';
mysql> GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';
通配符字符应使用 "%" 而不是 "*"。我遇到了一个奇怪的问题:
考虑以下内容:
db server: 192.168.0.101
web server: 192.168.0.102
如果在mysql.user中定义了两个用户,一个是'user'@'192.168.0.102'
,密码为password1,另一个是'user'@'192.168.0.%'
,密码为password2。
那么,如果你尝试使用密码为password2的'user'从Web服务器连接到数据库服务器,将导致"Access denied"(拒绝访问)错误,因为单个IP'user'@'192.168.0.102'
的认证比通配符'user'@'192.168.0.%'
的认证更优先。
MySQL 8.0.23及以上版本现在也支持CIDR表示法。
因此,基本上:
-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...
-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...
在连接服务器后,如果您想要在自己的主机上连接,应按照以下步骤进行:
GRANT ALL ON . to root@'write_your_ip_addres' IDENTIFIED BY 'write_password_to_connect'
;nano /etc/mysql/my.cnf
service mysql restart