原文:http://os.51cto.com/art/201202/318762.htm

根据原链接中“查看主机网卡流量”所写的实时流量监控脚本

监控linux主机流量的软件不少,之前一直用iptraf和dstat,

实际使用过程中dstat显示的速度与我cacti监测的数据不一致,(望知道原因的朋友不吝赐教)

iptraf和cacti监测到的速度一致,但似乎只有kbit/s和kbyte/s两种单位显示

 

cacti数据:

iptraf:

dstat:

 

遂自己写了个脚本,根据ifconfig中RX和TX计数字段,执行两次ifconfig,用第二次的数减去第一次的数实现

netspeed.sh

 

 

 
  
  1. #!/bin/bash 
  2. #network speed 
  3. #by wyyj12@163.com 
  4. #release 2012-11-13 
  5.  
  6. main() 
  7. while : 
  8. do 
  9. time=`date +%m"-"%d" "%k":"%M":"%S` 
  10. rx_before=`ifconfig $eth_name|grep "RX bytes"|awk '{print $2}'|cut -d ':' -f 2` 
  11. tx_before=`ifconfig $eth_name|grep "TX bytes"|awk '{print $6}'|cut -d ':' -f 2` 
  12. sleep 2 
  13. rx_after=`ifconfig $eth_name|grep "RX bytes"|awk '{print $2}'|cut -d ':' -f 2` 
  14. tx_after=`ifconfig $eth_name|grep "TX bytes"|awk '{print $6}'|cut -d ':' -f 2` 
  15.  
  16. rx_result=$[(rx_after-rx_before)/256] 
  17. tx_result=$[(tx_after-tx_before)/256] 
  18. echo -e "$time In_Speed: \E[30;42m"$[rx_result/speed]"\E[0m $unit Out_Speed: \E[30;42m"$[tx_result/speed]"\E[0m $unit" #绿 
  19. #echo -e "$time In_Speed:`tput rev`"$[rx_result/speed]"`tput sgr0` $unit Out_Speed: `tput rev`"$[tx_result/speed]"`tput sgr0` $unit" #反向色 
  20.  
  21. sleep 2 
  22. done 
  23.  
  24. #default 
  25. eth_name="eth0" 
  26. unit="Kbps" 
  27. speed="1" 
  28.  
  29. while getopts   hmMgGi: opt  
  30. do 
  31. case $opt in  
  32.     i) 
  33.         eth_name=$OPTARG 
  34.     ;; 
  35.     m|M) 
  36.         speed="1024" 
  37.         unit="Mbps" 
  38. #       echo -e  "\033[5m Count $eth_name use Mbps \033[0m" 
  39.     ;; 
  40.     g|G) 
  41.         speed="1048576" 
  42.         unit="Gbps" 
  43. #       echo -e  "\033[5m Count $eth_name use Gbps \033[0m" 
  44.     ;; 
  45.     h) 
  46.         echo  -e "  Usage:\t netspeed {-m|-M|-g|-G} [-i [interface]]" 
  47.                 echo  -e "  Default:\t Count eth0 use kbps " 
  48.         exit 0; 
  49.     ;; 
  50.     \?) 
  51.         echo "Usage: netspeed {-m|-M|-g|-G} [-i [interface]]" 
  52.         echo "Default : Count eth0 use kbps " 
  53.     ;; 
  54. esac 
  55. done 
  56.  
  57. echo -e  "\t\t \033[5m Count $eth_name speed ! \033[0m" 
  58. main