关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

在CentOS 云服务器上使用iptables屏蔽来自某个国家的IP?

发布时间:2023/7/12 11:21:46
香港云服务器

如果我们的云服务器持续受到某个国家的网络攻击,那么可以采取的一个措施就是屏蔽来自这个国家的所有IP。这篇文章介绍了如何使用iptables工具以及IP2LOCATION这家公司提供的IP地址库来屏蔽某个国家的IP。

第一步:安装iptables和ipset

yum install iptables ipset -yservice iptables start

第二步:下载iptables规则文件

我们使用IP2LOCATION这家公司提供的IP地址库。比如我们要屏蔽来自秘鲁的IP,请访问以下地址,选择国家为“秘鲁”,选择输出格式为“Linux iptables”,然后下载iptables规则文件。

https://www.ip2location.com/free/visitor-blocker

iptables规则文件下载到本地电脑后,用FTP软件或其他方式上传到云服务器上。

第三步:应用iptables规则

通过SSH方式远程到云服务器上,定位到刚才上传的iptables规则文件,并把文件重命名为block.txt。接下来,我们用脚本来处理这个规则文件。

创建一个脚本文件:

vi process.sh

脚本内容如下:

#!/bin/bash#
Script to process ip ranges to ban using IPSet and IPTables
ipset create countryblock hash:net
while read line; do ipset add countryblock $line; done < (block.txt)
iptables -I INPUT -m set --match-set countryblock src -j DROP

保存并执行脚本:

sh process.sh

最后,保存并加载iptables:

service iptables saveservice iptables reload

至此,我们已经成功在这台云服务器上屏蔽了来自秘鲁的IP。如果需要解除屏蔽,那么把脚本生成的iptables规则删除即可,注意需要再次保存iptables使其永久生效。