1、创建要封禁的IP配置文件
vim /path/iptables/deny_ip.conf
121.12.34.56
23.45.67.66
43.56.78.123
...
2、创建脚本将要封禁的IP批量导入 iptables
vim /path/deny_ip.sh
#!/bin/bash
# 通过 iptables 封禁 ip
# ip 封禁配置文件
DENY_IP_FILE="/alidata/data/iptables/deny_ip.conf"
while read -r ip; do
if ! /usr/sbin/iptables -C INPUT -s "$ip" -j DROP 2>/dev/null; then
/usr/sbin/iptables -I INPUT -s "$ip" -j DROP
fi
done < "$DENY_IP_FILE"
# 保存规则
iptables-save >/etc/iptables/rules.v4
3、执行 IP 导入脚本
sudo sh /path/deny_ip.sh
在 iptables 中,规则是按照从上到下的顺序匹配的,规则越多、越复杂,匹配时间越长。如果规则链中包含了大量复杂的规则(例如基于 IP、端口、协议等多重条件的匹配),可能会增加数据包处理的延迟。
例如,如果规则链中有大量 DROP 或 REJECT 规则,数据包需要逐条匹配,直到找到符合条件的规则,这可能会导致性能下降。
1、使用 ipset 工具将多个 IP 地址或端口集合化,减少规则数量,从而提高匹配效率。
2、将常用的规则放在规则链的前面,可以减少匹配时间。
性能提升:ipset 使用哈希表存储 IP 地址,匹配效率为 O(1),远高于 iptables 的 O(n)。
规则简洁:只需一条 iptables 规则即可匹配整个 IP 集合,避免规则链过长。
动态管理:可以随时向 ipset 集合中添加或删除 IP 地址,无需修改 iptables 规则。
#!/bin/bash
# 通过 iptables 配合 ipset 封禁 ip
DENY_IP_FILE="/path/deny_ip.conf"
IPSET_NAME="blacklist"
# 创建 ipset 集合(如果不存在)
if ! /usr/sbin/ipset list "$IPSET_NAME" &>/dev/null; then
/usr/sbin/ipset create "$IPSET_NAME" hash:ip
fi
# 添加 iptables 规则(如果不存在)| 这个是封禁所有端口
if ! /usr/sbin/iptables -C INPUT -m set --match-set "$IPSET_NAME" src -j DROP &>/dev/null; then
/usr/sbin/iptables -I INPUT -m set --match-set "$IPSET_NAME" src -j DROP
fi
# 添加 iptables 规则(如果不存在)| 只封禁 80 和 443 端口
#if ! /usr/sbin/iptables -C INPUT -m set --match-set "$IPSET_NAME" src -m multiport --dports 80,443 -j DROP &>/dev/null; then
# /usr/sbin/iptables -I INPUT -m set --match-set "$IPSET_NAME" src -m multiport --dports 80,443 -j DROP
#fi
# 从文件中读取 IP 并添加到 ipset 集合
while read -r ip; do
if ! /usr/sbin/ipset test "$IPSET_NAME" "$ip" &>/dev/null; then
/usr/sbin/ipset add "$IPSET_NAME" "$ip"
fi
done < "$DENY_IP_FILE"
# 删除不在文件中的 IP
/usr/sbin/ipset list "$IPSET_NAME" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | while read -r ip; do
if ! grep -Fxq "$ip" "$DENY_IP_FILE"; then
/usr/sbin/ipset del "$IPSET_NAME" "$ip"
fi
done
# 保存 ipset 和 iptables 规则
/usr/sbin/ipset save > /etc/ipset.conf
/usr/sbin/iptables-save > /etc/iptables/rules.v4
1、创建 ipset 集合
使用 ipset create
创建一个名为 blacklist
的哈希表集合,存储类型为 hash:ip
。
2、添加 iptables 规则
使用 iptables -I INPUT -m set --match-set blacklist src -j DROP
添加一条规则,匹配 blacklist 集合中的 IP 地址并丢弃。
3、批量添加 IP 地址
从 DENY_IP_FILE 文件中读取 IP 地址,并逐个添加到 blacklist 集合中。使用 ipset test 检查 IP 是否已存在,避免重复添加。
4、删除不在文件中的 IP:
使用 ipset list 获取集合中的所有 IP。
遍历集合中的 IP,如果 IP 不在 DENY_IP_FILE 文件中,则从集合中删除。
5、保存规则
使用 ipset save 和 iptables-save 分别保存 ipset 和 iptables 的规则,确保重启后规则仍然生效。
确保 DENY_IP_FILE 文件格式正确,每行一个 IP 地址。
如果集合中 IP 数量较多,删除操作可能会稍微耗时,但整体性能仍然优于逐条遍历的 iptables 规则。
通过以上修改,脚本能够动态同步 DENY_IP_FILE 文件和 ipset 集合中的 IP,确保规则的一致性。