使用shell/ target=_blank class=infotextkey>shell脚本计算linux网卡流量,方法中最关键点:
通过ifconfig eth0|grep bytes 得到输入输出的流量。
再将结果通过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