MySQL系列:限制IP访问,通过授权的方式实现

本文介绍了如何在MySQL数据库中管理用户访问权限,包括允许所有IP访问和限制特定IP或IP段访问的方法。可以通过直接修改user表或使用授权方式进行设置,并提供了相应的SQL语句示例。注意授权后需执行FLUSH PRIVILEGES使改动生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、允许用户所有IP访问

更改 mysql 数据库里的 user 表里的 host 项,从localhost"改成%即可。有两种方式可以实现。

第一种:直接修改user 表

1. mysql -u root -p  

2. select host,user from user where user='root';

3. update user set host = '%' where user='root' and host='localhost';  

4. select host, user from user where user='root';

第二种:授权的方式

grant all privileges on *.* to root@'%' identified by '123' with grant option;

flush privileges;


# *.* 表示所有的数据库 ,可以针对某个数据进行设置,如 on 库名.表名
# grant all privileges on 库名.表名 to '用户名'@'IP地址' identified by '密码' with grant option;

二、限制某个IP或者IP段访问

建议通过授权的方式实现。

#单个IP
grant all privileges on *.* to root@'192.168.1.3' identified by '123' with grant option;

flush privileges;

#IP段,使用%代替IP
grant all privileges on *.* to root@'192.168.1.%' identified by '123' with grant option;
or
grant all privileges on *.* to root@'192.168.%.%' identified by '123' with grant option;

flush privileges;

注意:

1、注意授权后必须FLUSH PRIVILEGES;否则无法立即生效。

2、高版本无法使用grant all privileges on *.* to "root"@"%" identified by "xxxx";去修改用户权限。

如:

mysql> SELECT @@VERSION;
+-----------+
| @@VERSION |
+-----------+
| 8.0.14    |
+-----------+

# 先创建远程用户,再授权
create user 'root'@'%' identified by  'password';

grant all privileges on *.* to 'root'@'%' with grant option;

flush privileges;

#查看
select User,Host from user;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值