linux-iptables安全加固脚本(可重复执行)

#!/bin/bash

chain_name="zgp" #自定义的规则链
ip_list="192.168.5.1" #ip地址,也可以填写网段:192.168.5.0/24
tcp_or_udp="tcp udp" #协议类型
tcp_port="22 1111" #tcp端口
udp_port="53 55" #udp端口
logfile="/tmp/iptable.log" #日志
######################################################################

#日志函数
log(){ echo -e 【INFO `date '+%Y-%m-%d %H:%M:%S'` `hostname`】 "\033[34m$1 \033[0m" |tee -a $logfile; }

#iptables保存函数
restart_iptables(){ log "save iptables." && service iptables save; }

#提示函数
Usage(){
log "\nUSAGE:\n 【 sh ./iptables.sh install ###配置自定义的iptables规则 】
【 sh ./iptables.sh remove ###移除自定义的iptables规则 】"
exit 0
}

#自定义链及规则
install(){
  log "Ready to add iptables. "
  chain_m=`iptables -L -n|grep "Chain $chain_name"|grep -v grep |wc -l`
if [ $chain_m -eq 0 ];then
  log "iptables -N $chain_name. " && iptables -N $chain_name
fi
for x in $tcp_or_udp;do
  case $x in
    "tcp")
      for y in $tcp_port;do
        log "iptables -A $chain_name -s $ip_list -p $x --dport $y -j ACCEPT. "
        iptables -A $chain_name -s $ip_list -p $x --dport $y -j ACCEPT
      done ;;
    "udp")
      for z in $udp_port;do
        log "iptables -A $chain_name -s $ip_list -p $x --dport $z -j ACCEPT. "
        iptables -A $chain_name -s $ip_list -p $x --dport $z -j ACCEPT
      done ;;
  esac
done
log "add $chain_name to chain INPUT. " && iptables -A INPUT -j $chain_name
log "set chain INPUT DROP" && iptables -P INPUT DROP
}

#移除链及规则
remove(){
  log "set chain INPUT ACCEPT." && iptables -P INPUT ACCEPT
  n=`iptables -nL INPUT --line-numbers |grep -w -o $chain_name|wc -l`
if [ ${n} -ne 0 ];then
  log "remove chain $chain_name from INPUT" && iptables -D INPUT `iptables -nL INPUT --line-numbers |grep $chain_name|awk '{print $1}'`
fi
  log "clean chain $chain_name. " && iptables -F $chain_name && iptables -X $chain_name
}


case $1 in
  'install')
    remove; install; restart_iptables ;;
  'remove')
    remove && restart_iptables ;;
  *)
    Usage ;;
esac

posted @ 2019-12-31 10:39  丶鹏  阅读(530)  评论(0编辑  收藏  举报