banner
moeyy

moeyy

一条有远大理想的咸鱼。
github
mastodon
email

Linux VPS使用WonderShaper限制伺服器上傳/下載頻寬

** 說明:** 最近看到有人問博主如何限制伺服器的上傳帶寬,所以就分享一下之前常用的一個限速腳本WonderShaper,原理的話,網上有比較詳細的解釋是WonderShaper使用tc來定義流量調整命令,使用QoS來處理特定的網絡介面。外發流量通過放在不同優先級的隊列中,達到限制傳出流量速率的目的;而傳入流量通過丟包的方式來達到速率限制的目的。使用起來挺方便的,有需求的可以了解一下。

使用#

項目地址:點擊訪問

安裝的話可以直接用軟體包安裝,不過版本都不太新,所以這裡直接從Github拉取最新原始碼。

1、安裝依賴

#Debian/Ubuntu系統
apt install -y make git

#CentOS系統
yum install make git -y

2、安裝 WonderShaper

git clone https://github.com/magnific0/wondershaper.git
cd wondershaper
make install

3、設置限速

#使用命令
USAGE: wondershaper [-hcs] [-a <adapter>] [-d <rate>] [-u <rate>]

OPTIONS:
   -h           顯示此消息
   -a <adapter> 設置介面
   -d <rate>    設置最大下載速率(以Kbps為單位)和/或
   -u <rate>    設置最大上傳速率(以Kbps為單位)
   -p           在/etc/conf.d/wondershaper.conf中使用預設值
   -c           清除介面的限制
   -s           顯示介面的當前狀態
   -v           顯示當前版本

首先查看網卡:

#這裡提供三個可以查看網卡的命令,建議使用第一個
ifconfig
ip addr
route

比如我要限制eth0網卡速度,使用命令:

#限制上傳帶寬為10M
wondershaper -a eth0 -u 10240
#限制下載帶寬為10M
wondershaper -a eth0 -d 10240
#限制上傳和下載均為10M
wondershaper -a eth0 -d 10240 -u 10240
#清除網卡限速規則
wondershaper -c -a eth0

然後我們可以測一下速度,使用命令:

wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py
chmod +x speedtest-cli
./speedtest-cli

請輸入圖片描述

請輸入圖片描述

這是沒有限速前的測速:

上傳 / 下載限速10M後的測速:

開機自啟#

一般設置限速規則後,伺服器重啟的話,限速規則會自動失效,所以這裡需要稍微設置一下,使其開機也自動生效,這裡就說2種方法。

1、使用 rc.local
這是最簡單的設置自啟方法,不過Debian 9Ubuntu 17+是沒有rc.local文件的,所以使用該系統的需要先配置一下。

1、添加rc-local.service,以下為一整條命令,一起複製運行
cat > /etc/systemd/system/rc-local.service <<EOF
[Unit]
Description=/etc/rc.local
ConditionPathExists=/etc/rc.local
 
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
 
[Install]
WantedBy=multi-user.target
EOF

2、新建rc-local文件,以下為一整條命令,一起複製運行
cat > /etc/rc.local <<EOF
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.    
EOF

3、添加權限並設置開機自啟
chmod +x /etc/rc.local
systemctl start rc-local
systemctl enable rc-local

最後將啟動命令加入rc.local文件,使用命令:

#CentOS 7系統
echo "wondershaper -a eth0 -d 10240 -u 10240" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local

#CentOS 6、Debian、Ubuntu系統
echo "wondershaper -a eth0 -d 10240 -u 10240" >> /etc/rc.local
chmod +x /etc/rc.local

這裡限速命令自行修改。

2、使用 Systemd
由於安裝時,Systemd配置文件也給你了,所以就方便使用了,不過該方法只適用於CentOS 7Debian 8+Ubuntu 16+等。

由於啟動時,默認調用的配置文件為/etc/conf.d/wondershaper.conf,所以先編輯該文件:

nano /etc/conf.d/wondershaper.conf

大致如下:

[wondershaper]
# Adapter
#
IFACE="eth0"

# Download rate in Kbps
#
DSPEED="10240"

# Upload rate in Kbps
#
USPEED="10240"

參數依次為網卡、下載、上傳限制,修改好了後,使用Ctrl+xy保存退出。

再啟動並開機自啟:

systemctl start wondershaper
systemctl enable wondershaper
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。