tc流控脚本 ,动态保证每个ip有1M带宽

tc主脚本:

#!/bin/bash

#

. /root/tc_functions

NUM=2

DEV=eth0

init_tc $NUM

while : ; do

#IP=`netstat  -antup|grep ESTABLISHED |grep  80|cut -d ":" -f8`

IP=`netstat -antup|grep ESTABLISHED|grep 80|awk '{print $5}' |grep  -o  "\([0-9]\{1,3\}\.\)\{1,3\}[0-9]\{1,3\}"|sort  -rn |uniq -c|awk '{print $2}'`

free=0

for  i  in $IP

do

IP16=`ip_to_16 $i`

if  tc -s filter ls dev $DEV | grep $IP16 &>/dev/null ;then

continue;

fi 

for x in `seq $NUM`

do

change $x

if [  $free -eq 1 ];then

tc filter add dev $DEV parent 1: protocol ip prio 16 u32 match ip dst $i flowid 1:$x ;

free=0;

break 1;

fi

done

done

 tc filter add dev $DEV parent 1: protocol ip prio 16 u32 match ip dst 0.0.0.0/0 flowid 1:$[$NUM+1] ;

sleep 30

tc filter del dev eth0 parent 1: protocol ip prio 16 u32;

done





tc_functions:


function hd(){

case $1 in

10)

echo a;;

11)

echo b;;

12)

echo c;;

13)

echo d;;

14)

echo e;;

15)

echo f;;

*)

echo $1;;

esac

}

function ip_to_16(){

a=`echo $1|cut -d '.' -f1 `

b=`echo $1|cut -d '.' -f2 `

c=`echo $1|cut -d '.' -f3 `

d=`echo $1|cut -d '.' -f4 `

a1=$[$a/16]

a2=$[$a%16]

b1=$[$b/16]

b2=$[$b%16]

c1=$[$c/16]

c2=$[$c%16]

d1=$[$d/16]

d2=$[$d%16]

q1=`hd $a1` 

q2=`hd $a2`

q3=`hd $b1` 

q4=`hd $b2` 

q5=`hd $c1` 

q6=`hd $c2` 

q7=`hd $d1` 

q8=`hd $d2`

echo $q1$q2$q3$q4$q5$q6$q7$q8 

}

function change(){

        PAST=`tc -s class ls dev $DEV|grep  Sent |cut -d ' ' -f3|head -$1|tail -1`

        sleep 1

        NOW=`tc -s class ls dev $DEV|grep  Sent |cut -d ' ' -f3|head -$1|tail -1`

        [ $NOW  -eq $PAST ]&& free=1

}

function init_tc(){

tc qdisc del dev eth0 root

tc qdisc add dev eth0 root handle 1: htb r2q 1

local i 

for  i  in `seq $1`

do

tc class add dev eth0 parent 1: classid 1:$i htb rate 1mbit ceil 1mbit

done

tc class add dev eth0 parent 1: classid 1:$[$i+1] htb rate 2mbit ceil 2mbit

}


你可能感兴趣的:(流控,tc)