本文介绍了计算linux网卡流量的一个shell脚本,一个通过固定间隔时间获取ifconfig eth0 的字节值而计算出网卡流量的方法,有需要的朋友参考下。
使用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 if [ -n "$1" ]; then eth_name=$1 else eth_name="eth0" fi if [ -n "$2" ]; then all_time=$2 else all_time=900 fi i=0 v1_b=`ifconfig $eth_name | grep bytes | awk '{print $6}' | awk -F : '{print $2}'` v2_b=`ifconfig $eth_name | grep bytes | awk '{print $2}' | awk -F : '{print $2}'` v1_t=$v1_b v2_t=$v2_b #echo "$v1_t" while [ $i -le $all_time ]; do sleep 1 v1_c=`ifconfig $eth_name | grep bytes | awk '{print $6}' | awk -F : '{print $2}'` #echo "$v1_c" v2_c=`ifconfig $eth_name | grep bytes | awk '{print $2}' | awk -F : '{print $2}'` i=`expr $i + 1` v1_rate=`expr ( $v1_c - $v1_t ) / 1024` v2_rate=`expr ( $v2_c - $v2_t ) / 1024` v_rate=`expr ( $v1_rate + $v2_rate ) ` v1_t=$v1_c v2_t=$v2_c v1_avg_rate=`expr ( $v1_c - $v1_b ) / $i / 1024` v2_avg_rate=`expr ( $v2_c - $v2_b ) / $i / 1024` v_avg_rate=`expr ( $v1_avg_rate + $v2_avg_rate ) ` clear echo "=========================================================" echo "`date`" echo "send: $v1_rate KB/s accept: $v2_rate KB/s netrate: $v_rate KB/s avg send: $v1_avg_rate KB/s avg accept: $v2_avg_rate KB/s avg rate: $v_avg_rate KB/s" echo "==========================================================" done