Linux/Unix 系统的防火墙 iptables 规则,在添加的时候并不会检查该规则是否已经存在,即便已经存在,它在添加时还会再添加一遍。然而 iptables的匹配规则是按顺序的,这对性能是有一定的影响的。

本文介绍两种方式对 iptables 规则进行去重

方法1

添加前,先用测试是否存在规则,测试命令:

iptables -L -n

测试结果:

# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state ESTABLISHED
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 8
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22

 

新建检测脚本

vim iptables_filter.sh 

#!/bin/bash
#
# mimvp.com
# 2017.05.20

function check_iptables() {
    # $@ is all params
    check=$(echo $@ | sed -e 's/-A/-C/g')
    echo $check

    # $? is recent param
    is_iptables=`echo "$check" | grep iptables | grep -v grep | wc -l`
    if [ -z $is_iptables ]; then
        iptables $check; ret=$?
    else
        $check; ret=$?
    fi
    if [ "$ret" -eq 0 ]; then
        echo "iptables exist to no insert";    # exit 0
    else
        echo "iptables no exist to insert" # xtables-multi iptables $@
    fi
}

echo $@
check_iptables $@

测试结果:

# ./iptables_filter.sh iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -C INPUT -p tcp --dport 22 -j ACCEPT
iptables exist to no insert
[root@mimvp_hk script]# 
# ./iptables_filter.sh iptables -A INPUT -p tcp --dport 23 -j ACCEPT 
iptables -A INPUT -p tcp --dport 23 -j ACCEPT
iptables -C INPUT -p tcp --dport 23 -j ACCEPT
iptables: Bad rule (does a matching rule exist in that chain?).
iptables no exist to insert

 

插入一条,查看iptables结果:

# iptables -A INPUT -p tcp --dport 22 -j ACCEPT 
[root@mimvp_hk script]# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state ESTABLISHED
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 8
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22

 

方法2

iptables 规则存储文件路径为: 

/etc/sysconfig/iptables

shell 处理iptables文件去重复,然后导入生效

#!/bin/bash
#
# mimvp.com
# 2017.05.20

cat /etc/sysconfig/iptables | sed  -n "G; s/\n/&&/;/^\(.*\n\).*\n\1/d; s/\n//;h;P" > /tmp/iptables
iptables-restore < /tmp/iptables
rm -f /tmp/iptables

/etc/init.d/iptables save
iptables-save > /etc/sysconfig/iptables

 

 

参考推荐

10个常用iptables配置实例

iptables 详细介绍及配置

iptables日志探秘

CentOS 7 安装 iptables 防火墙

Linux iptables防火墙与DDOS攻防实战