Created
January 4, 2021 22:51
-
-
Save zarzen/3cbfe7d022e4e71bd6febb67ac51daae to your computer and use it in GitHub Desktop.
根据IP限制带宽
This file contains hidden or 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 | |
# 注意:这个脚本只有对本地有用,比如node0 上做了限制,但是iperf -s 在node0上运行 | |
# node1 连接到 node0 通过iperf -c node0-ip -P5 这样的情况带宽无法得到限制 | |
# 只能是node0 连接其他node时候这个限制有作用 | |
# 原代码链接: https://serverfault.com/questions/191560/how-can-i-do-traffic-shaping-in-linux-by-ip | |
NETCARD=ens5 # 改这边 | |
MAXBANDWIDTH=40000 # 选个大点的就行 | |
# reinit | |
tc qdisc del dev $NETCARD root handle 1 | |
tc qdisc add dev $NETCARD root handle 1: htb default 9999 | |
# create the default class | |
tc class add dev $NETCARD parent 1:0 classid 1:9999 htb rate $(( $MAXBANDWIDTH ))mbit ceil $(( $MAXBANDWIDTH ))mbit burst 15k prio 9999 | |
# control bandwidth per IP | |
declare -A ipctrl | |
# 改这边 | |
# define list of IP and bandwidth (in mbit/s) below | |
ipctrl[172.31.79.244]="30000" # 30Gbps | |
ipctrl[172.31.76.23]="5000" # 5Gbps | |
mark=0 | |
for ip in "${!ipctrl[@]}" | |
do | |
mark=$(( mark + 1 )) | |
bandwidth=${ipctrl[$ip]} | |
# traffic shaping rule | |
tc class add dev $NETCARD parent 1:0 classid 1:$mark htb rate $(( $bandwidth ))mbit ceil $(( $bandwidth ))mbit burst 15k prio $mark | |
# netfilter packet marking rule | |
iptables -t mangle -A INPUT -i $NETCARD -s $ip -j CONNMARK --set-mark $mark | |
# filter that bind the two | |
tc filter add dev $NETCARD parent 1:0 protocol ip prio $mark handle $mark fw flowid 1:$mark | |
echo "IP $ip is attached to mark $mark and limited to $bandwidth mbps" | |
done | |
#propagate netfilter marks on connections | |
iptables -t mangle -A POSTROUTING -j CONNMARK --restore-mark |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment