想要實時查看Linux流量情況,又不想再去下第三方工具,可以直接寫腳步運行!
系統:CentOS 6.5
原理:從/proc/net/dev中獲取到流量情況,再通過換算並除以間隔時間來得到流量單位M
#------------------
#Author:Administrator
#Created:2015-04-10
#------------------
#!/bin/bash
#使用方法
usage()
{
echo "useage: $0 ethname intervel"
exit 0
}
#網口配置
if [ $# -gt 1 ];then
ethname=$1
num=`ifconfig|grep ${ethname}|wc -l`
if [ $num -gt 0 ];then
ethname=$1
else
echo "Can't find $ethname,Please Check"
exit 1
fi
fi
#時間配置
intervel=1
if [ $# -gt 0 ]; then
interval=$2
test=`expr "$interval" \* 0`
if [ "$test" != "0" ]; then
echo "Invalid <interval> param '$interval' . It should be a integer number. Usage: $0 ethname intervel"
exit -1
fi
if [ $interval -lt 1 ]; then
echo "Invalid <interval> param '$interval' . It should be > 0 (seconds). Usage: $0 ethname intervel"
exit -1
fi
fi
#函數判斷
if [ $# -ne 2 ]
then
usage
fi
echo "$0 is starting,Device is $1,Intervel is $2"
echo -e "\n"
typeset Rev old_Rev
eth=$1
intervel=$2
old_Rev=`cat /proc/net/dev|grep $eth| awk '{print $1}'| awk -F : '{print $2}'`
old_Send=`cat /proc/net/dev|grep $eth|awk '{print $9}'`
#echo "old_Rev is $old_Rev"
#echo "Old_send is $old_Send"
while true
do
sleep $intervel
Rev=`cat /proc/net/dev|grep $eth|awk '{print $1}'|awk -F : '{print $2}'`
Send=`cat /proc/net/dev|grep $eth|awk '{print $9}'`
#echo "Rev is $Rev"
#echo "Send is $Send"
diff_1=`awk -v Rev=$Rev -v old_Rev=$old_Rev -v intervel=$intervel 'BEGIN{printf "Receive is %6.2f", ( Rev - old_Rev ) / 1024 / 1024 / intervel * 8}'`
diff_2=`awk -v Send=$Send -v old_Send=$old_Send -v intervel=$intervel 'BEGIN{printf "Send is %6.2f", ( Send - old_Send ) / 1024 / 1024 / intervel * 8}'`
echo "`date +'%Y-%m-%d %H:%M:%S'` Speed: IN ${diff_1} mbps OUT ${diff_2} mbps"
old_Rev=$Rev
old_Send=$Send
done