Linux iptables 规则的去重方法
1,314 views
0
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
参考推荐:
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2017-10-25 01:46:39
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!