vps 自动限速脚本
买的一个z.com的vps,据说1小时内不能超过10Gytes,长时间20mbps流量。
通过iptables获得OUTPUT出口的 目的ip地址,然后通过 cron 调用脚本,tc 自动插值。
#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin
IPT=$(which iptables)
TC=$(which tc)
DOWNLINK=2560
interface=eth0
case “$1” in
start)
echo “ratelimit start.”
ipignore=”1″;for ip in $ipignore; do echo $wan_addr.$ip >> /tmp/ipignore_dato.lst;done
$IPT -t mangle -F POSTROUTING
IPT=$(which iptables)
for i in eth0;do
$IPT -t mangle -I POSTROUTING -o $i -m connbytes –connbytes-mode bytes –connbytes-dir both –connbytes 409600: -m recent –name lan –rdest –set
$IPT -t mangle -I POSTROUTING 1 -o $i -m connbytes –connbytes-mode bytes –connbytes-dir both –connbytes 0:204800 -m recent –name lan –rdest –remove;done
$TC qdisc del dev $interface root 2> /dev/null > /dev/null
$TC qdisc add dev $interface root handle 1: htb default 3
$TC class add dev $interface parent 1: classid 1:1 htb rate $((DOWNLINK))kbps
$TC class add dev $interface parent 1:1 classid 1:2 htb rate $((DOWNLINK*50/100))kbps ceil $((DOWNLINK*100/100))kbps
##rerate rule
$TC class add dev $interface parent 1:1 classid 1:3 htb rate $((DOWNLINK*50/100))kbps ceil $((DOWNLINK*95/100))kbps quantum 1400 prio 1
$TC qdisc add dev $interface parent 1:3 handle 3: sfq perturb 10
#fq_codel limit 800 quantum 300 noecn
;;
stop)
echo “ratelimit stop.”
$IPT -t mangle -F POSTROUTING
$TC qdisc del dev $interface root 2> /dev/null > /dev/null
;;
rerate)
echo “ratelimit rerate.”
#for i in eth0;do
#$IPT -t mangle -I POSTROUTING -o $i -m connbytes –connbytes-mode bytes –connbytes-dir both –connbytes 768000: -m recent –name lan –rdest –set
#$IPT -t mangle -I POSTROUTING 1 -o $i -m connbytes –connbytes-mode bytes –connbytes-dir both –connbytes 0:512000 -m recent –name lan –rdest –remove;done
#sleep 5;
cat /proc/net/xt_recent/lan|awk ‘{print $1}’ |awk -F”=” ‘{print $2}’|awk ‘!i[$1]++’>/tmp/u150.lst
while read uip;do sed -i -e “/${uip}$/d” /tmp/u150.lst;done </tmp/ipignore_dato.lst
$TC filter del dev eth0 parent 1:0 protocol ip prio 20
IP=51;for i in `cat /tmp/u150.lst`;
do echo “`(date +”%m/%d/%Y %T”)` $IPT_limit $i successfully_” >> /tmp/log
$TC class del dev $interface parent 1:2 classid 1:$IP
#$TC qdisc del dev $interface parent 1:$IP
$TC class add dev $interface parent 1:2 classid 1:$IP htb rate $((DOWNLINK*8/100))kbps ceil $((DOWNLINK*16/100))kbps quantum 1400 prio 0
$TC qdisc add dev $interface parent 1:$IP handle $IP: sfq perturb 10
#fq_codel limit 800 quantum 300 noecn
$TC filter add dev $interface parent 1: protocol ip prio 20 u32 match ip dst $i flowid 1:$IP;
let “IP+=1”;done;
#iptables -t mangle -F POSTROUTING #for i in 6 5 4 3 2 1;do iptables -t mangle -D POSTROUTING $i;done;killall all_conn_dato.sh
;;
restart|force-reload)
$0 stop
sleep 1
$0 start
;;
*)
echo “ratelimi script”
echo “Usage: $0 {start|stop|restart|rerate}”
exit 1
esac
exit 0