教程集 www.jiaochengji.com
教程集 >  脚本编程  >  shell  >  正文 shell awk实时监控网卡流量的脚本

shell awk实时监控网卡流量的脚本

发布时间:2014-11-19   编辑:jiaochengji.com
本文介绍下,用shell与awk结合,以实现实时统计网卡流量的一段脚本,有需要的朋友参考下。

学习用shell脚本结合awk命令实时统计网卡流量。

原理:
 

[chengmo@localhost ~]$ cat /proc/net/dev
Inter-|   Receive     |  Transmit
face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo:1068205690 1288942839    0    0    0     0          0         0 1068205690 1288942839    0    0    0     0       0          0
  eth0:91581844 334143895    0    0    0     0          0 145541676 4205113078 3435231517    0    0    0     0       0          0
 

说明,proc/net/dev 文件保存了网卡总流量信息,通过间隔一段间隔,将入网卡与出记录加起来。减去之前就得到实际速率

代码:
 

复制代码 代码示例:
awk 'BEGIN{
OFMT="%.3f";
devf="/proc/net/dev";
while(("cat "devf) | getline)
{
    if($0 ~ /:/ && ($10+0) > 0)
    {
        split($1,tarr,":");
        net[tarr[1]]=$10+tarr[2];
        print tarr[1],$10+tarr[2];
    }
}
close(devf);
while((system("sleep 1 ")) >=0)
{
    system("clear");
    while( getline < devf )
    {
        if($0 ~ /:/ && ($10+0) > 0)
            {
                split($1,tarr,":");
                if(tarr[1] in net)
                {
                    print tarr[1],":",($10+tarr[2]-net[tarr[1]])*8/1024,"kb/s";
                    net[tarr[1]]=$10+tarr[2];
                }      
            }   
    }
    close(devf);
}
}'

代码说明:
第一个while 是获得总的初始值,$1是网卡出流量,$10是网卡进流量。
第2个while会间隔1秒钟启动一次。计算总流量差得到平均每秒流量。

注意:
通过getline 逐行读取文件,需要close关闭 。
否则在第2次while循环中不能获得数据。

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

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