使用shell指令碼計算Linux網卡流量,方法中最關鍵點:
複製代碼 代碼如下:
ifconfig $eth_name | grep bytes | awk '{print $6}' | awk -F : '{print $2}'
通過ifconfig eth0|grep bytes 得到輸入輸出的流量。
複製代碼 代碼如下:
/@rac2=>dd2$ifconfig eth0|grep bytes
RX bytes:1638005313300 (1.4 TiB) TX bytes:3408060482049 (3.0 TiB)
再將結果通過awk 得出所要的欄位值。
固定時間得到這些值,在寫個迴圈計算一下就能得到網卡流量。
完整代碼:
代碼一:
#!/bin/bash# 統計網卡流量# link:www.jb51.net# date:2013/2/26n=10 daterm -rf /tmp/ifconfig_logwhile (( $n >= 0 ))do n=$(($n - 1)); date >> /tmp/ifconfig_log ifconfig eth1 >> /tmp/ifconfig_log sleep 1done grep "RX bytes:" /tmp/ifconfig_log | awk -F"[:| ]" '{print $13}' | awk 'BEGIN{tmp=$1}{if(FNR > 1)print $1-tmp}{tmp=$1}'
代碼二:
#!/bin/bashif [ -n "$1" ]; then eth_name=$1else eth_name="eth0"fii=0send_o=`ifconfig $eth_name | grep bytes | awk '{print $6}' | awk -F : '{print $2}'`recv_o=`ifconfig $eth_name | grep bytes | awk '{print $2}' | awk -F : '{print $2}'`send_n=$send_orecv_n=$recv_owhile [ $i -le 100000 ]; do send_l=$send_n recv_l=$recv_n sleep 1 send_n=`ifconfig $eth_name | grep bytes | awk '{print $6}' | awk -F : '{print $2}'` recv_n=`ifconfig $eth_name | grep bytes | awk '{print $2}' | awk -F : '{print $2}'` i=`expr $i + 1` send_r=`expr $send_n - $send_l` recv_r=`expr $recv_n - $recv_l` total_r=`expr $send_r + $recv_r` send_ra=`expr \( $send_n - $send_o \) / $i` recv_ra=`expr \( $recv_n - $recv_o \) / $i` total_ra=`expr $send_ra + $recv_ra` sendn=`ifconfig $eth_name | grep bytes | awk -F \( '{print $3}' | awk -F \) '{print $1}'` recvn=`ifconfig $eth_name | grep bytes | awk -F \( '{print $2}' | awk -F \) '{print $1}'` clear echo "==================================================" echo "Last second : Send rate: $send_r Bytes/sec Recv rate: $recv_r Bytes/sec Total rate: $total_r Bytes/sec" echo "Average value: Send rate: $send_ra Bytes/sec Recv rate: $recv_ra Bytes/sec Total rate: $total_ra Bytes/sec" echo "Total traffic after startup: Send traffic: $sendn Recv traffic: $recvn" echo "=================================================="done
代碼三:
#!/bin/bash # Link: www.51bbo.com ### while : do Time=`date +%F” “%T.%N` rx_before=`ifconfig eth0 |sed -n 8p |awk ‘{print $2}'| cut -c7-` tx_before=`ifconfig eth0 |sed -n 8p |awk ‘{print $6}'| cut -c7-` sleep 2 rx_after=`ifconfig eth0 |sed -n 8p |awk ‘{print $2}'| cut -c7-` tx_after=`ifconfig eth0 |sed -n 8p |awk ‘{print $6}'| cut -c7-` rx_result=$[(rx_after – rx_before)/512] tx_result=$[(tx_after – tx_before)/512] echo -e “$Time nNow_In_Speed: ‘$rx_result'Kbps Now_OUt_Speed: ‘$tx_result'Kbpsn” done