linux下屏蔽大量非法ip地址

本文是通过ipset命令配合iptables规则对大量非法ip进行屏蔽。

1.安装ipset命令

1
2
#安装ipset
yum install ipset

2. ipset命令相关应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#删除iplist
ipset destroy banthis

#创建规则:
ipset create banthis hash:net maxelem 1000000

#添加规则:
ipset add banthis 1.1.1.1/32

#列出规则:
ipset list

#保存规则:
ipset save banthis -f banthis.txt

#编辑规则:
vim banthis.txt

#导入iplist
ipset restore -f banthis.txt

3. 配置iptables规则

1
2
3
4
5
6
7
8
9
#iptables执行规则
iptables -I INPUT -m set --match-set banthis src -p tcp --destination-port 80 -j DROP

#查找所有规则
iptables -L INPUT --line-numbers

#删除一条规则
iptables -D INPUT 11 (注意,这个11是行号,是iptables -L INPUT --line-numbers 所打印出来的行号)
##次数说明,比如你删除第一条规则后,其后的规则都会发生变化,所以建议每删除一条就进行查看一次ip。有些规则不能删哦。。

4. 实例

a. 清空需要配置的规则名称

1
[root@localhost ~]# ipset destroy banthis

b. 编辑配置文件

1
2
3
4
5
6
7
8
[root@localhost ~]#vim banthis.txt
##文件内容写法:
create banthis hash:net family inet hashsize 1024 maxelem 1000000
add banthis 1.179.183.27

##create 后是名称
##hash:net 代表的是集合的类型。IP集有多个类型。hash:net类型的IP集使用哈希来存储多个CIDR块。
##maxelem 1000000 设置ip个数上限

c.导入配置文件

1
2
3
[root@localhost ~]#ipset restore -f banthis.txt
确保成功:
[root@localhost ~]#ipset list

d.加入iptables配置规则

1
2
3
4
5
6
7
8
[root@localhost ~]#iptables -I INPUT -m set --match-set banthis src -p tcp --destination-port 80 -j DROP
#查看规则是否生效:
[root@localhost ~]#iptables -L INPUT --line-numbers
##如果看到字样
num target prot opt source destination
1 DROP tcp -- anywhere anywhere match-set banthis src tcp dpt:http

##则说明it is oook.

e. 删除规则

1
[root@localhost ~]#iptables -D INPUT 1
---------------- 谢谢光临 ----------------

本文标题:linux下屏蔽大量非法ip地址

文章作者:pxrux

发布时间:2018年09月27日 - 14:09

最后更新:2019年08月13日 - 09:08

原始链接:http://www.mykernel.cn/linux-work-3.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%