对Linux Server限速以模拟低速网络环境
<!-- lang: shell -->
#!/bin/bash
#
# limite net rate
#
# if su
if [[ $EUID -ne 0 ]]; then
echo ""
echo "You must be a root user" 2>&1
echo ""
exit 1
fi #[[ $EUID -ne 0 ]];
# for help
if [ $# -lt 1 ] || [ "$1" = "-h" ]; then
echo "Limit TX(output transmit) of some Port on the specified Interface."
echo "By Honghe @ Ruijie."
echo ""
echo "For help:"
echo "Usage: $0 -h"
echo " "
echo "Set the speed of Port in a Interface:"
echo "Usage: $0 'rate KB/s' 'interface' 'port'"
echo "Example: $0 5 eth0 8000"
echo " "
echo "Release speed limit:"
echo "Usage: $0 -r 'interface'"
echo "Example: $0 -r eth0"
echo " "
echo "Show stat:"
echo "Usage: $0 -s 'interface'"
echo "Example: $0 -s eth0"
echo " "
exit 0
elif [ $# -lt 3 ]; then
# show status.
if [[ "$1" = "-s" ]]; then
LIMIT_DEV="$2"
echo ""
tc -s qdisc ls dev ${LIMIT_DEV}
echo ""
iptables -t mangle --list
elif [[ "$1" = "-r" ]]; then
# release.
LIMIT_DEV="$2"
iptables -t mangle -F
tc qdisc del dev ${LIMIT_DEV} root
echo " "
echo "Speed limit released."
echo " "
else
echo ""
echo "Syntax wrong, use -h for help."
echo ""
fi #[[ "$1" = "-s" ]]
else
# set limit
#RATE Kilobytes per second
# LIMIT_RATE=1
# LIMIT_PORT=8000
# LIMIT_DEV="eth0"
LIMIT_RATE=$1
LIMIT_DEV="$2"
LIMIT_PORT=$3
# delete existing rule
tc qdisc del dev ${LIMIT_DEV} root > /dev/null 2>&1
# Turn on queuing discipline, enter:
tc qdisc add dev ${LIMIT_DEV} root handle 1:0 htb
# Define a class with limitations i.e. set the allowed bandwidth to 512 Kilobytes and burst bandwidth to 640 Kilobytes for port 80:
tc class add dev ${LIMIT_DEV} parent 1:0 classid 1:10 htb rate ${LIMIT_RATE}kbps ceil ${LIMIT_RATE}kbps prio 0
# Finally, assign it to appropriate qdisc:
tc filter add dev ${LIMIT_DEV} parent 1:0 prio 0 protocol ip handle 10 fw flowid 1:10
# Please note that port 80 is NOT defined anywhere in above class. You will use iptables mangle rule as follows:
iptables -t mangle -F
iptables -A OUTPUT -t mangle -p tcp --sport ${LIMIT_PORT} -j MARK --set-mark 10
# print
echo " "
echo "Set speed limit: interface ${LIMIT_DEV} port ${LIMIT_PORT} as ${LIMIT_RATE} KB/s"
echo " "
fi #[ $# -lt 1 ] || [ "$1" = "-h" ];
#
# Reference:
# http://www.cyberciti.biz/faq/linux-traffic-shaping-using-tc-to-control-http-traffic/
#