CentOS7使用ipset快速屏蔽指定国家的IP访问
ipset是iptables的扩展,它允许你创建匹配整个IP地址集合的规则。可以快速的让我们屏蔽某个IP段。这里分享个屏蔽指定国家访问的方法,有时候还可以有效的帮网站阻挡下攻击。
方法
首先需要得到国家IP段,下载地址:http://www.ipdeny.com/ipblocks/ 这里以我们国家为例。
1.安装ipset
yum -y install ipset
2.创建规则
#创建一个名为cnblocks的规则
ipset -N cnblocks hash:net
#下载国家IP段到当前目录
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
#将IP段添加到cnblocks规则中(firewalld)
for i in $(cat /root/cn.zone ); firewall-cmd --permanent --ipset=cnblocks --add-entry=$i; done
CentOS7中自带的是firewalld,添加到规则中时用上面这条命令
如果你换成了iptables,那就用下面这条命令
#将IP段添加到cnblocks规则中(iptables)
for i in $(cat /root/cn.zone ); do ipset -A cnblocks $i; done
3.开始屏蔽
#firewalld
firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source ipset=cnblocks drop'
firewall-cmd --reload
#iptables
iptables -I INPUT -p tcp -m set --match-set cnblocks src -j DROP
service iptables save
4.解除屏蔽
#firewalld
firewall-cmd --permanent --remove-rich-rule='rule family=ipv4 source ipset=cnblocks drop'
firewall-cmd --permanent --delete-ipset=cnblocks
firewall-cmd --reload
#iptables
iptables -D INPUT -p tcp -m set --match-set cnblocks src -j DROP
ipset destroy cnblocks
service iptables save