之前看到过使用类似方法统计流量的脚本,今天完善了一下:
#!/bin/bash #filename:Monitor_NIC #sh Monitor_NIC ethX while : do Rx_Sum=`ifconfig $1 | sed -n '8p' |awk '{print $3,$4}'| tr -d '[()]'` Tx_Sum=`ifconfig $1 | sed -n '8p' |awk '{print $7,$8}'| tr -d '[()]'` Rx_Before=`ifconfig $1 | sed -n '8p'| awk '{print $2}'| tr -c -d '0-9\n'` Tx_Before=`ifconfig $1 | sed -n '8p'| awk '{print $6}'| tr -c -d '0-9\n'` sleep 1 Rx_After=`ifconfig $1 | sed -n '8p'| awk '{print $2}'| tr -c -d '0-9\n'` Tx_After=`ifconfig $1 | sed -n '8p'| awk '{print $6}'| tr -c -d '0-9\n'` Rx=`echo "scale=4;($Rx_After-$Rx_Before)/1024"|bc` Tx=`echo "scale=4;($Tx_After-$Tx_Before)/1024"|bc` Rx_Judge=`echo $Rx|cut -b 1` Rx_2=`echo $Rx|awk -F "." '{print $2}'` [ $Rx_Judge == "." ]&&Rx=0.${Rx_2} Tx_Judge=`echo $Tx|cut -b 1` Tx_2=`echo $Tx|awk -F "." '{print $2}'` [ $Tx_Judge == "." ]&&Tx=0.${Tx_2} echo "Rx: ${Rx} kbps">/mnt/.$1.log echo "Tx: ${Tx} kbps">>/mnt/.$1.log echo "*${1}:*"|grep $1 --color=yes echo "=========================================" cat /mnt/.$1.log|column -t;echo DATE=`date "+%H:%M:%S %Y.%m.%d"` echo "Rx: $Rx_Sum " echo "Tx: $Tx_Sum " echo -e "\t\t\t $DATE" echo "=========================================" echo;echo done
演示: [iyunv@localhost ~]# sh Monitor_NIC eth0
*eth0:* ========================================= Rx: 1.4472 kbps Tx: 23.6562 kbps
Rx: 229.2 GiB Tx: 20.3 GiB 17:35:45 2013.05.19 =========================================
*eth0:* ========================================= Rx: 3.9726 kbps Tx: 104.9746 kbps
Rx: 229.2 GiB Tx: 20.3 GiB 17:35:46 2013.05.19 =========================================
*eth0:* ========================================= Rx: 1.6611 kbps Tx: 19.2207 kbps
Rx: 229.2 GiB Tx: 20.3 GiB 17:35:47 2013.05.19 =========================================
|