iptables+ipset实现黑白名单
温馨提醒
一、安装
二、创建 ipset 黑名单和白名单集合
说明:
hash:net 可接受网段和单个IP
hash:ip 只接受单个IP
三、添加 IP/网段 到集合中
添加黑名单
添加白名单
四、使用 iptables 应用规则
放行白名单IP(优先)
| |
拒绝黑名单IP(在白名单之后执行)
| |
五、保存规则
写入配置文件
1ipset save > /etc/ipset.conf设置开机自动加载
vim /etc/systemd/system/ipset-restore.service1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17[Unit] Description=Restore IP sets from /etc/ipset.conf Before=iptables.service [Service] Type=oneshot ExecStart=/bin/sh -c '/usr/sbin/ipset restore < /etc/ipset.conf' RemainAfterExit=yes [Install] WantedBy=multi-user.target systemctl daemon-reexec systemctl daemon-reload systemctl enable ipset-restore systemctl enable iptables保存 iptables 规则
验证
六、清空规则
七、删除集合
提示:如果在 iptables 中引用了某个 ipset 集合,需要先删除 iptables 中的对应规则,再删除该集合,否则会报错