教程集 www.jiaochengji.com
教程集 >  脚本编程  >  shell  >  正文 shell脚本计算Linux网卡流量

shell脚本计算Linux网卡流量

发布时间:2014-12-20   编辑:jiaochengji.com
本文介绍了计算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

您可能感兴趣的文章:
计算网卡流量的shell脚本(代码分享)
shell脚本计算Linux网卡流量
linux shell 监控网卡流量的脚本(入门参考)
一个测试网卡流量的shell脚本
实时监测vps主机流量的shell脚本
shell awk实时监控网卡流量的脚本
监控网卡流量的shell脚本分享
检测网卡流量的shell脚本
统计网卡流量的二个shell脚本(ifconfig)(图文)
监测内存使用量、剩余量及网卡流量的shell脚本

关键词: linux shell  shell  网卡  网卡流量   
[关闭]
~ ~