Centos6监控端口流量并对流量大小做控制

这个脚本会根据提供的端口,监控端口的进出口流量,如果流量大于设置节点,则阻止此端口流量。实际使用将脚本放到/root/目录下执行即可。

脚本机制:

脚本运行时,会在脚本当前目录建立flowcheck目录,之后会根据相应监控端口生成相应文件夹,文件夹内含有监控脚本以及相关文件。

#!/bin/bash
  dir=$(cd `dirname $0`;pwd)
  dir=$dir/flowcheck
  read -p "请输入要监控的端口号:" net
  read -p "请输入要监控的流量大小(以G为单位):"  flow_size
  mkdir $dir/$net
  touch $dir/$net/input
  touch $dir/$net/output
  touch $dir/$net/${net}.sh
  #显示监控端口流量
  iptables -A INPUT -p tcp --dport $net
  iptables -A OUTPUT -p tcp --sport $net
(
cat << EOF
while true; 
do
  iptables -L -v -n|grep $net|awk '{print \$2}'|sed -n '1p' >> $dir/$net/input
  iptables -L -v -n|grep $net|awk '{print \$2}'|sed -n '2p' >> $dir/$net/output
  sleep 10
  out=\$(tail -n 1 $dir/$net/output |tr -cd "[A-Z]")
  in=\$(tail -n 1 $dir/$net/input |tr -cd "[A-Z]")
  case \$out in
     G)
        flow_input=\$(tail -n 1 $dir/$net/input|awk 'BEGIN{FS="G"}{print \$1}')
	flow_output=\$(tail -n 1 $dir/$net/output|awk 'BEGIN{FS="G"}{print \$1}')
        if [[ \$flow_input -ge $flow_size ]] || [[ \$flow_output -ge $flow_size ]];then
      #将端口的流量阻挡
	   iptables -A OUTPUT -p tcp --sport $net -j DROP
           iptables -A INPUT -p tcp --sport $net -j DROP
	   mv $dir/$net $dir/${net}_overload
           ps aux|grep $net|grep -v 'grep $net'|awk '{print \$2}'|xargs kill -9
	fi
     ;;
   esac
   case \$in in
    G)
        flow_input=\$(tail -n 1 $dir/$net/input|awk 'BEGIN{FS="G"}{print \$1}')
        flow_output=\$(tail -n 1 $dir/$net/output|awk 'BEGIN{FS="G"}{print \$1}')
        if [[ \$flow_input -ge $flow_size ]] || [[ \$flow_output -ge $flow_size ]];then
           iptables -A OUTPUT -p tcp --sport $net -j DROP
           iptables -A INPUT -p tcp --sport $net -j DROP
           mv $dir/$net $dir/${net}_overload
	   ps aux|grep $net|grep -v 'grep $net'|awk '{print \$2}'|xargs kill -9
        fi
    ;;
   esac
done
EOF
) > $dir/$net/${net}.sh
nohup sh $dir/$net/${net}.sh & >/dev/null 2>&1

下面是使用此脚本后,实际中会使用的几个小命令,做个备注:

iptables -nL --line-number  #iptables规则数字标记。  如下:

Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination         
1               tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8521 
2               tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:2147 

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination         
1               tcp  --  0.0.0.0/0            0.0.0.0/0           tcp spt:8521 
2               tcp  --  0.0.0.0/0            0.0.0.0/0           tcp spt:2147 

iptables -D INPUT 2   #删除相应数字标记规则

以上。

你可能感兴趣的:(shell,centos)