今天写改进的一份流量监控脚本,经测试可用,给大家看下
#!/bin/bash
# Date
2014.03.13
# Author fengxxxx
# Function 实时检查系统的网络流量的大小
function networkdownup(){
local nic=$1
R1=`cat /sys/class/net/$nic/statistics/rx_bytes`
T1=`cat /sys/class/net/$nic/statistics/tx_bytes`
sleep 1
R2=`cat /sys/class/net/$nic/statistics/rx_bytes`
T2=`cat /sys/class/net/$nic/statistics/tx_bytes`
TBPS=`expr $T2 - $T1`
RBPS=`expr $R2 - $R1`
TKBPS=`expr $TBPS / 1024`
RKBPS=`expr $RBPS / 1024`
echo "上传速率 $nic: $TKBPS kb/s 下载速率 $nic: $RKBPS kb/s at $(date +%Y%m%d%H:%M:%S)"
}
# run : 指定运行的检测次数,如果输入的次数为空,测默认检测10次
function run(){
#num count default value = 10
num=${1:-10} ;
local nic=$2 ;
while [ $num -gt 0 ]
do
networkdownup $nic;
num="$((num-1))"
done
}
#检测一下字符是否是数学
# 如是是,就返回1 ;如是不是,就返回0
# use echo to pass retval
function checkInt(){
local foo=$1
if [[ $foo != *[!0-9]* ]]; then
# echo "'$foo' is strictly numeric"
echo 1
else
#echo "'$foo' has a non-digit somewhere in it"
echo 0
fi
}
### use return to pass retval
function checkInt2(){
local foo=$1
if [[ $foo != *[!0-9]* ]]; then
# echo "'$foo' is strictly numeric"
return 1
else
#echo "'$foo' has a non-digit somewhere in it"
return 0
fi
}
####################### shell exec #####################
# method 1
#retval=$(checkInt $1)
# method 2
time=${1:-10}
checkInt2 $time
retval=$?
if [ $retval -eq 0 ] ;then
echo -e "检测的时间为数字(s),比如: sh network.sh [seconds] [nic] \ndefalut is sh network.sh 10 eth0 "
exit 1
fi
nic=${2:-"eth0"}
falg_nic=0
### check the nic is exist ??
for var in `ls /sys/class/net/ -F | grep "@"`
do
[ "$nic" == "${var%@}" ] && nic="${var%@}" && falg_nic=1
done
if [ $falg_nic -eq 1 ];then
run $time $nic
else
echo "Sorry ,$nic don't exist ."
fi[/code]
分享至: