当前位置: > shell编程 >

使用shell监控网络的实时流量

时间:2014-09-08 22:49来源:linux.it.net.cn 作者:it
使用shell监控网络的实时流量

shell文件,monitor_traffic.sh。

复制代码代码如下:

#!/bin/bash
function usage
{
  echo "Usage: $0 "
  echo "e.g. $0 eth0 2"
  exit 1
}

if [ $# -lt 2 ];then
   usage
fi

eth=$1
interval=$2

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

while true
do
   sleep ${interval}
   in=$(cat /proc/net/dev | grep -w $eth | sed -e "s/\(.*\)\:\(.*\)/\2/g" | awk '{ print $1 }' )
   out=$(cat /proc/net/dev | grep -w $eth | sed -e "s/\(.*\)\:\(.*\)/\2/g" | awk '{ print $9 }')
   sub_in=$(( ($in-$in_old)/$interval ))
   sub_out=$(( ($out-$out_old)/$interval ))
   echo "Recv rate: $((${sub_in}/1024)) KB/s   Sent rate:  $((${sub_out}/1024)) KB/s "
   in_old=${in}
   out_old=${out}
done
exit 0

输出如下
Recv rate: 1175 KB/s Sent rate: 29 KB/s 
Recv rate: 1175 KB/s Sent rate: 29 KB/s 
Recv rate: 1179 KB/s Sent rate: 31 KB/s 
Recv rate: 987 KB/s Sent rate: 33 KB/s 
Recv rate: 1159 KB/s Sent rate: 29 KB/s 
Recv rate: 1167 KB/s Sent rate: 29 KB/s 
Recv rate: 1082 KB/s Sent rate: 27 KB/s 
Recv rate: 1085 KB/s Sent rate: 27 KB/s 
Recv rate: 1129 KB/s Sent rate: 29 KB/s 
Recv rate: 954 KB/s Sent rate: 24 KB/s 
Recv rate: 465 KB/s Sent rate: 18 KB/s 
Recv rate: 507 KB/s Sent rate: 14 KB/s 
Recv rate: 1135 KB/s Sent rate: 30 KB/s
 
与dstat命令的对比dstat -n -N peth1
1176k 30k
1176k 30k
1180k 31k
 987k 33k
1159k 29k
1167k 30k
1083k 27k
1085k 27k
1129k 29k
 955k 24k
 466k 19k
 508k 15k
1135k 30k

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