#!/bin/bash
#SPEED=`/bin/bash /etc/zabbix/script/flow.sh |cut -d ‘.‘ -f1`
SPEED=`/bin/bash /root/flow.sh |cut -d ‘.‘ -f1`
[ -z $SPEED ]&& SPEED=1
EXIST=`iptables -n -v -L |grep CC-FLOW|wc -l`
if [ $SPEED -gt 1250 ];
then
IP=`netstat -antup|grep ESTABLISHED|awk ‘{print $5}‘ |grep -o "\([0-9]\{1,3\}\.\)\{1,3\}[0-9]\{1,3\}"|sort -rn |uniq -c|awk ‘{print $2}‘` #awk截取客户端字段、sort 和uniq是防止ip重复
if [ $EXIST -eq 0 ];then
iptables -N CC-FLOW #创建自定义链CC-FLOW
iptables -A OUTPUT -j CC-FLOW #把OUTPUT规则引到CC-FLOW
fi
for i in $IP
do
x=`iptables -n -v -L |grep $i|wc -l`
if [ $x -ne 0 ];then
continue
fi
iptables -A CC-FLOW -d $i -m limit --limit 150/s -j ACCEPT #限制$i下载输入为每秒150个包,一个包一般是1540字节左右,所以速度大概在200kbyte
iptables -A CC-FLOW -d $i -j DROP #超过的drop
done
else
if [ $EXIST -ne 0 ] && [ $SPEED -lt 500 ]; then
iptables -F CC-FLOW #清空cc-flow的规则
iptables -D OUTPUT -j CC-FLOW #清空cc-flow与output的链接,否则删除不了链接
iptables -X CC-FLOW #删除cc-flow链
fi
fi
flow.sh计算流量脚本:
#!/bin/bash
old_inbw=`cat /proc/net/dev | grep eth0 | awk -F‘[: ]+‘ ‘{print $3}‘`
old_outbw=`cat /proc/net/dev | grep eth0 | awk -F‘[: ]+‘ ‘{print $11}‘`
sleep 5
new_inbw=`cat /proc/net/dev | grep eth0 | awk -F‘[: ]+‘ ‘{print $3}‘`
new_outbw=`cat /proc/net/dev | grep eth0 | awk -F‘[: ]+‘ ‘{print $11}‘`
inbw=$[ $new_inbw - $old_inbw ]
outbw=$[ $new_outbw - $old_outbw ]
# echo "eth0: IN:$inbw bytes OUT:$outbw bytes"
IN=`echo "scale=2;$inbw/5/1024" |bc |awk ‘{printf "%.2f\n", $0}‘`
OUT=`echo "scale=2;$outbw/5/1024" |bc |awk ‘{printf "%.2f\n", $0}‘`
echo "$IN+$OUT" |bc
old_inbw=${new_inbw}
old_outbw=${new_outbw}
var0=$[$var0 + 1]