简单几行命令实现限流 frp 端口 ip 服务器 tc

要实现对本地某个端口进行限流,这种需求我是在搭建内外网穿透服务器时遇到的。

#! /bin/bash
/sbin/tc qdisc del dev eth0 root # remove all rules.
/sbin/tc qdisc add dev eth0 root handle 1:0 htb default 10
/sbin/tc class add dev eth0 parent 1:0 classid 1:10 htb rate 80kbps ceil 90kbps prio 0 # rate 80k, top 90k
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport XXXX -j MARK --set-mark 10 # apply rule on port XXXX
/sbin/service iptables save
tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 10 fw flowid 1:10
# add this script to /etc/rc.local, which will run afte reboot automatically.

如上面代码所示,实现了对XXXX端口限流,速率80kbps,最高90kbps。参考自https://www.cyberciti.biz/faq/linux-traffic-shaping-using-tc-to-control-http-traffic/。该文还给出了对80和22端口进行限流的示例,如下:

/sbin/tc qdisc add dev eth0 root handle 1: htb
/sbin/tc class add dev eth0 parent 1: classid 1:1 htb rate 1024kbps
/sbin/tc class add dev eth0 parent 1:1 classid 1:5 htb rate 512kbps ceil 640kbps prio 1
/sbin/tc class add dev eth0 parent 1:1 classid 1:6 htb rate 100kbps ceil 160kbps prio 0
/sbin/tc filter add dev eth0 parent 1:0 prio 1 protocol ip handle 5 fw flowid 1:5
/sbin/tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 6 fw flowid 1:6
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport 80 -j MARK --set-mark 5
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport 22 -j MARK --set-mark 6

此外,还找到了对一些列ip进行限流的案例,来自https://serverfault.com/questions/191560/how-can-i-do-traffic-shaping-in-linux-by-ip

#! /bin/bash
NETCARD=eth0
MAXBANDWIDTH=100000

# 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 ))kbit ceil $(( $MAXBANDWIDTH ))kbit burst 5k prio 9999

# control bandwidth per IP
declare -A ipctrl
# define list of IP and bandwidth (in kilo bits per seconds) below
ipctrl[192.168.1.1]="256"
ipctrl[192.168.1.2]="128"
ipctrl[192.168.1.3]="512"
ipctrl[192.168.1.4]="32"

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 ))kbit ceil $(( $bandwidth ))kbit burst 5k 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 kbps"
done

#propagate netfilter marks on connections
iptables -t mangle -A POSTROUTING -j CONNMARK --restore-mark

你可能感兴趣的:(杂项)