禁止国外IP
禁止国外IP
- 安装
ipset
:
apt install ipset -y
说明:使用 ufw+ipset
来阻挡国外IP,首先需要安装 ipset
工具。
- 创建地址表:
ipset create china hash:net hashsize 10000 maxelem 1000000
说明:创建名为 china
的地址表,采用 hash:net
类型,哈希表大小为 10000
,最大元素数量为 1000000
。
- 下载中国IP段文件:
wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone
说明:从指定网址下载包含中国IP段的文件。
- 生成添加IP到地址表的脚本:
for i in `cat cn.zone`doecho ""ipset add china $i"" >> ipset_result.shdone
说明:遍历 cn.zone
文件中的每一行IP地址,生成将这些IP添加到 china
地址表的命令,并写入 ipset_result.sh
文件中。
- 赋予脚本执行权限并运行:
chmod +x ipset_result.sh./ipset_result.sh
说明:为 ipset_result.sh
脚本添加可执行权限,然后运行该脚本,将中国IP段添加到 china
地址表中。
- 查看地址表内容:
ipset list china
说明:查看 china
地址表中已添加的IP段信息。
- 配置
ufw
规则:
vi /etc/ufw/after.rules
在打开的文件中添加以下内容:
#add-A ufw-after-input -p tcp --dport 80 -m set --match-set china src -j ACCEPT
说明:编辑 ufw
的后置规则文件,添加一条规则,允许来自 china
地址表中的IP段通过TCP协议访问80端口。
- 管理
ufw
防火墙:
ufw enableufw disableufw reload
说明:分别为启用防火墙、禁用防火墙、重新加载防火墙规则的命令。
- 测试访问:
http://192.168.21.195/
说明:访问指定地址进行测试。
- 添加内网IP到地址表:
ipset add china 192.168.21.0/16ipset add china 192.167.21.0/16
说明:由于内网访问也需要,所以将内网的IP段添加到 china
地址表中。