当前位置: 首页 > 工具软件 > ipset > 使用案例 >

iptables之ipset使用介绍

梁华清
2023-12-01

ipset是什么?
ipset是iptables的扩展,它允许你创建 匹配整个地址集合的规则。而不像普通的iptables链只能单IP匹配, ip集合存储在带索引的数据结构中,这种结构即时集合比较大也可以进行高效的查找,
除了一些常用的情况,比如阻止一些危险主机访问本机,从而减少系统资源占用或网络拥塞,IPsets也具备一些新防火墙设计方法,并简化了配置.
官网:http://ipset.netfilter.org/
1、ipset安装

yum安装: yum install ipset
源代码安装:进官网下载ipset-6.30.tar.bz2 ,
yum -y install libmnl-devel libmnl
tar -jxvf ipset-6.30.tar.bz2  && cd ipset-6.30 && ./configure --prefix=/usr/local/ipset && make && make install   完成安装

2.创建ipset集合:

[root@localhost ~]# which ipset
/usr/sbin/ipset
[root@localhost ~]# ipset --list
[root@localhost ~]# ipset create zabbix_server hash:net
[root@localhost ~]# ipset add zabbix_server 192.168.1.20
[root@localhost ~]# ipset create mysql_server hash:net
[root@localhost ~]# ipset add mysql_server 192.168.1.20
[root@localhost ~]# ipset --list
Name: zabbix_server
Type: hash:net
Header: family inet hashsize 1024 maxelem 65536 
Size in memory: 16784
References: 0
Members:
192.168.1.20

Name: mysql_server
Type: hash:net
Header: family inet hashsize 1024 maxelem 65536 
Size in memory: 16784
References: 0
Members:
192.168.1.20

3.保存规则到ipset文件:

[root@localhost ~]# /etc/init.d/ipset save
ipset: Saving IP sets to /etc/sysconfig/ipset:             [确定]

[root@localhost ~]# cat /etc/sysconfig/ipset 
create zabbix_server hash:net family inet hashsize 1024 maxelem 65536 
add zabbix_server 192.168.1.20
create mysql_server hash:net family inet hashsize 1024 maxelem 65536 
add mysql_server 192.168.1.20

4.iptables规则文件:

[root@localhost ~]# cat /etc/sysconfig/iptables
#Generated by iptables-save v1.4.7 on Wed Jul 31 10:21:39 2019
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [10988:6938377]
-A INPUT -s 118.32.234.103/32 -j DROP 
-A INPUT -i lo -j ACCEPT 
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
-A INPUT -p tcp -m multiport --dports 80,81,82,443 -m state --state NEW -j ACCEPT 
-A INPUT -s 211.144.68.140/32 -p tcp -m multiport --dports 10050,3306 -j ACCEPT 
-A INPUT -p tcp -m set --match-set zabbix_server src -m tcp --dport 10050 -j ACCEPT 
-A INPUT -p tcp -m set --match-set mysql_server src -m tcp --dport 3306 -j ACCEPT 
-A INPUT -p tcp -m multiport --dports 570,21,1038 -j ACCEPT 
-A INPUT -p icmp -m icmp --icmp-type 8 -m limit --limit 5/sec --limit-burst 10 -j ACCEPT 
-A INPUT -j DROP 
COMMIT

5.命令行添加iptables规则并保存:

iptables -I INPUT -m set --match-set mysql_server src -p tcp -m multiport --dports 10050,3306 -j ACCEPT 
iptables -I INPUT -m set --match-set rsync_server src -p tcp              --dport 873 -j ACCEPT
service iptables save
/etc/init.d/iptables save

6.ipset del使用:

ipset del删除规则时,必须重启iptables服务才会生效

ipset del jump_mysql 111.206.110.202
重启iptables才能生效

ipset add 添加规则时,不用重启iptables 就会生效

 类似资料: