最近比較忙,好久沒更新部落格了,今天剛好不忙寫了一個流量監控指令碼.測試在centos下已通過,有需要的朋友可以試試,有BUG或者需要添加其他功能話可以留言哦.
一、指令碼源碼
# vi /etc/rc.d/traffic_monitor.sh
----------------------------------------------
複製代碼 代碼如下:
#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin;
export PATH
function traffic_monitor {
# 系統版本
OS_NAME=$(sed -n '1p' /etc/issue)
# 網口名
eth=$1
#判斷網卡存在與否,不存在則退出
if [ ! -d /sys/class/net/$eth ];then
echo -e "Network-Interface Not Found"
echo -e "You system have network-interface:\n`ls /sys/class/net`"
exit 5
fi
while [ "1" ]
do
# 狀態
STATUS="fine"
# 擷取當前時刻網口接收與發送的流量
RXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')
TXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')
# 擷取1秒後網口接收與發送的流量
sleep 1
RXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')
TXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')
clear
# 擷取這1秒鐘實際的進出流量
RX=$((${RXnext}-${RXpre}))
TX=$((${TXnext}-${TXpre}))
# 判斷接收流量如果大於MB數量級則顯示MB單位,否則顯示KB數量級
if [[ $RX -lt 1024 ]];then
RX="${RX}B/s"
elif [[ $RX -gt 1048576 ]];then
RX=$(echo $RX | awk '{print $1/1048576 "MB/s"}')
$STATUS="busy"
else
RX=$(echo $RX | awk '{print $1/1024 "KB/s"}')
fi
# 判斷髮送流量如果大於MB數量級則顯示MB單位,否則顯示KB數量級
if [[ $TX -lt 1024 ]];then
TX="${TX}B/s"
elif [[ $TX -gt 1048576 ]];then
TX=$(echo $TX | awk '{print $1/1048576 "MB/s"}')
else
TX=$(echo $TX | awk '{print $1/1024 "KB/s"}')
fi
# 列印資訊
echo -e "==================================="
echo -e "Welcome to Traffic_Monitor stage"
echo -e "version 1.0"
echo -e "Since 2014.2.26"
echo -e "Created by showerlee"
echo -e "BLOG: http://www.showerlee.com"
echo -e "==================================="
echo -e "System: $OS_NAME"
echo -e "Date: `date +%F`"
echo -e "Time: `date +%k:%M:%S`"
echo -e "Port: $1"
echo -e "Status: $STATUS"
echo -e " \t RX \tTX"
echo "------------------------------"
# 列印即時資料流量
echo -e "$eth \t $RX $TX "
echo "------------------------------"
# 退出資訊
echo -e "Press 'Ctrl+C' to exit"
done
}
# 判斷執行參數
if [[ -n "$1" ]];then
# 執行函數
traffic_monitor $1
else
echo -e "None parameter,please add system netport after run the script! \nExample: 'sh traffic_monitor eth0'"
fi
----------------------------------------------
二、執行效果
複製代碼 代碼如下:
# sh traffic_monitor.sh eth0