Last active
December 25, 2023 01:32
-
-
Save kona3266/349b6c8ac0840e4fc0908c08b7e7cb2e to your computer and use it in GitHub Desktop.
tc-bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#set -x | |
function usage() | |
{ | |
echo "Usage:" | |
echo " tc.sh -d <dev> -b <bandwidth> -m <mode> --src <src_ip>" | |
echo " <dev> is the device which tc be attached to" | |
echo " <bandwidth> unit is Mb" | |
echo " <mode> 0 contains class while 1 does not, default 0" | |
echo " <src_ip> match source ip default empty" | |
echo " eg: tc.sh -d eth0 -b 1" | |
} | |
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then | |
usage | |
exit 1 | |
fi | |
mode="0" | |
src_ip="" | |
while [ True ]; do | |
if [ "$1" == "-d" ];then | |
device=$2 | |
shift 2 | |
elif [ "$1" == "-b" ];then | |
bandwidth=$2 | |
shift 2 | |
elif [ "$1" == "-m" ];then | |
mode=$2 | |
shift 2 | |
elif [ "$1" == "--src" ]; then | |
src_ip=$2 | |
shift 2 | |
else | |
break | |
fi | |
done | |
if [ -z $device ] || [ -z $bandwidth ]; then | |
usage | |
exit 1 | |
fi | |
bandwidth=$[$bandwidth*1024] | |
if [ "$mode" == "0" ]; then | |
tc qdisc del dev $device root 2>/dev/null | |
tc qdisc add dev $device root handle 1: htb | |
tc class add dev $device parent 1: classid 1:10 htb rate "${bandwidth}kbit" burst 128k | |
if [ -z "$src_ip" ]; then | |
tc filter add dev $device protocol ip parent 1: prio 1 basic flowid 1:10 | |
else | |
tc filter add dev eth0 protocol ip parent 1: prio 1 u32 match ip src $src_ip flowid 1:10 | |
fi | |
elif [ "$mode" == "1" ]; then | |
#another method is use filter directly on root egress qdisc | |
tc qdisc del dev $device root 2>/dev/null | |
tc qdisc add dev eth0 root handle 1: htb | |
if [ -z "$src_ip" ]; then | |
tc filter add dev eth0 parent 1: protocol ip prio 1 basic police rate 1024kbit burst 128k mtu 65535 drop | |
else | |
tc filter add dev eth0 parent 1: protocol ip prio 1 u32 match ip src $src_ip police rate "${bandwidth}kbi t" burst 128k mtu 65535 drop | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment