Linux 使用 tc 与 iptables 限制服务器输出流量

对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/
#

转载于:https://my.oschina.net/leopardsaga/blog/173204

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值