租虛擬主機很常碰到流量限制的問題。若不小心洩漏IP,惡意人士刻意做 DDOS 攻擊,導致超流斷線那還好,但有些服務是超流之後不斷線,反而是多收$$

如:知名的 Digitialocean
1
每月限制 1TB 的 transfer,詳細查一下官方文件可以看到有一段超流的收費。

Do you charge for bandwidth?

Yes. Plans start with 1TB per month and increase incrementally. Once the monthly transfer limit has been exceeded, the cost of bandwidth is $0.02 per GB over the limit.
引述自 — https://www.digitalocean.com/help/policy/

因此,我們還是要試著自己監控流量,必要時採許相對應措施。


vnstat : linux 頻寬監測工具,可以根據小時、日、周等等單位統計頻寬使用狀況。

crontab : linux 排程工具,這邊將利用crontab 定時排程檢查流量是否超過限制,並做相對應措施。

1. 安裝 vnstat

sudo apt-get install vnstat

2. 列出目前系統可監控的網卡

vnstat --iflist
1

3. 這邊以有線網卡 eth0 舉例,設定要監控流量的網卡及更新流量資訊

vnstat -u -i eth0

4. 啟動 vnstat

sudo service vnstat start

5. 可以透過以下指令確認使否成功啟動

ps aux | grep "vnstat"
1

6. 測試監控流量狀況

vnstat
1

7. 完成,接下來寫個 shell script (check.sh) 來執行檢查流量。(其中用到 awk 這個簡單語言,處理 command line的輸出,幫助我們抽取流量資訊)

1. 利用 awk 抽取出總流量資訊。
2. 判斷是否大於 999 GiB,如果大於則關閉機器。


#!/bin/bash
ax=`vnstat --oneline | awk -F ";" '{print $11}'`
if [[ "$ax" == *GiB* ]];
then
 if [ $(echo "$(echo "$ax" | sed 's/ GiB//g') > 999"|bc) -eq 1 ]
 then
 shutdown -h now
 fi
fi

 

參考來源:
http://pastebin.com/2vXMBaSi

8. 完成 shellscript ,我們將他加入例行性排程並且以root身分執行(一般使用者會無法存取部分資料夾),定時檢查流量

編輯/etc/crontab

加入

# m h  dom mon dow user   command
10  *    *       *        *        root   bash check.sh

crontab 詳細用法請參考 — http://linux.vbird.org/linux_basic/0430cron.php

 

1 Comment

Leave a Reply