当前位置: > shell编程 >

实时监测vps主机流量的shell脚本

时间:2014-07-09 13:28来源:linux.it.net.cn 作者:IT网

在linux中,实时流量监控不外乎两种方法。

方法1,可以安装iftop,通过ascii图形化显示实时流量数据,比较直观明显。
方法2,就是本文要分享的这种,用shell脚本采集/proc/net/dev中的实时数据,不依赖任何安装包,对于内网linux服务器很有用。

脚本如下:
 

复制代码代码示例:

#!/bin/bash
# test network width
# edit by www.jbxue.com

# usage
function usage
{
   echo "Usage: $0  "
   echo "    e.g. $0 eth0 2"
   exit 65
}

if [ $# -lt 2 ];then
usage
fi
typeset in in_old dif_in
typeset out out_old dif_out
typeset timer
typeset eth

eth=$1
timer=$2

in_old=$(cat /proc/net/dev | grep $eth | sed -e "s/\(.*\)\:\(.*\)/\2/g" | awk ' { print $1 }' )
out_old=$(cat /proc/net/dev | grep $eth | sed -e "s/\(.*\)\:\(.*\)/\2/g" | awk ' { print $9 }' )

while true
do
sleep ${timer}
in=$(cat /proc/net/dev | grep $eth | sed -e "s/\(.*\)\:\(.*\)/\2/g" | awk ' { print $1 }' )
out=$(cat /proc/net/dev | grep $eth | sed -e "s/\(.*\)\:\(.*\)/\2/g" | awk ' { print $9 }' )
dif_in=$(((in-in_old)/timer))
dif_out=$(((out-out_old)/timer))
echo "IN: ${dif_in} Byte/s OUT: ${dif_out} Byte/s "
in_old=${in}
out_old=${out}
done
exit 0

脚本说明:
本脚本需要二个参数。
参数1, 网卡设备号,一般就是 eth0;参数2,统计间隔的秒数,2 表示2秒计算一次。
流量统计单位是 Byte/s。

(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容