基于 ipset 封 IP 或 IP 段

小初seo 学习笔记769字数 790阅读2分38秒阅读模式
摘要

在写 iptables 防火墙策略时,一条一条写封 IP 的策略会让后期维护非常困难,特别是 IP 特别多时

在写 iptables 防火墙策略时,一条一条写封 IP 的策略会让后期维护非常困难,特别是 IP 特别多时。

比如常规的封 IP 的 命令如下:

iptables -I INPUT -s 43.158.214.10 -j DROP

当 IP 数量很多时,这样的策略要写好几百条,后期增删都非常麻烦。我们可以用 ipset 来简单这个过程。

首先创建一个 ipset,比如我们把集合名叫 hw:

ipset create hash:net hw

创建完 ipset 后就可以启用 iptables 策略了:

iptables -I INPUT -m set --match-set hw src -j DROP

后续就只用在 ipset 中加 IP 或 IP 段了:

ipset add hw 61.147.15.65ipset add hw 61.147.15.70ipset add hw 61.147.21.51-61.147.21.60

删除也很方便,只用将 add 换成 del 即可:

ipset del hw 61.147.15.65ipset del hw 61.147.15.70ipset del hw 61.147.21.51-61.147.21.60

当 ipset 中的对象已存在时,执行 add 时会失败。如果相清空 ipset 后重新添加,可以执行 flush 操作。

ipset flush hw

当需要删除 ipset 集合时,需要先删除 iptables 规则,再删除 ipset。删 iptables 规则需要指定规则号:

$ iptables -nL INPUT --line-number| headChain INPUT (policy ACCEPT)num  target     prot opt source               destination1    DROP       all  --  0.0.0.0/0            0.0.0.0/0            match-set hw src
$ iptables -D INPUT 1$ ipset destroy hw

查看 ipset 内容的命令为:

ipset list hw

  • 本文由 发表于 2023年8月25日 00:33:58
  • 转载请务必保留本文链接:https://www.pkak.cn/9820.html