Linux使用iptables和ipset屏蔽指定国家IP访问的方法

发表时间:2019-10-16 10:48 | 分类:Linux | 浏览:1,594 次

ipset是iptables的一个扩展,可以创建IP集,设置iptables规则更加灵活、高效和美观。基于这种特性,在linux中可以禁止某个国家的IP访问,也可以设置智能中国IP访问的白名单。

第一步

获取国家IP地址段,下载地址:http://www.ipdeny.com/ipblocks/ 。

第二步

安装ipset扩展

#Debian/Ubuntu系统
apt-get -y install ipset

#CentOS系统
yum -y install ipset

第三步

创建规则,例如中国IP的集合。

#创建一个名为cnip的规则
ipset -N cnip hash:net
#下载国家IP段
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
#将IP段添加到cnip规则中
for i in $(cat /root/cn.zone ); do ipset -A cnip $i; done

第四步

屏蔽中国IP访问(注意如果是从中国SSH到服务器,以下操作会导致服务器无法连接,谨慎操作!)

iptables -I INPUT -p tcp -m set --match-set cnip src -j DROP

解除屏蔽

iptables -D INPUT -p tcp -m set --match-set cnip src -j DROP

这样屏蔽指定国家IP访问的需求就已经实现,如果服务器或者网站被攻击,可以用这个方法试下。另外可以试用“moerats”分享的一键脚本快速屏蔽。

使用演示

wget https://raw.githubusercontent.com/zhangnq/scripts/master/bash/block-ips.sh
chmod +x block-ips.sh
./block-ips.sh

屏蔽

ipset_block_country_japan_ip

查看

ipset_block_country_japan_ip2

参考:https://www.moerats.com/archives/585/

本文标签:

本文链接:https://www.sijitao.net/3142.html

欢迎您在本博客中留下评论,如需转载原创文章请注明出处,谢谢!

一键脚本 博客历程 留言联系 文章归档 网站地图 谷歌地图
Copyright © 2010-2024 章郎虫博客 All Rights Reserved.