计算网卡流量详解程序员

#!/bin/bash 
 
if [ $# -ne 2 ];then 
    echo -e "/e[1;31mUsage:/t/t./net.sh device time(second)/e[0m" 
    echo -e "/e[1;31mExample:/t./net.sh eth0 2/e[0m" 
    exit 1 
fi 
time=$2 
old_in=$(awk -v dev=$1 '{if($0~dev)print $2}' /proc/net/dev) 
old_out=$(awk -v dev=$1 '{if($0~dev)print $10}' /proc/net/dev) 
 
while true 
do 
    sleep $time 
    dev_in=$(awk -v dev=$1 '{if($0~dev)print $2}' /proc/net/dev) 
    dev_out=$(awk -v dev=$1 '{if($0~dev)print $10}' /proc/net/dev) 
    dif_in=$((((dev_in-old_in)/time/1000)*8)) 
    dif_out=$((((dev_out-old_out)/time/1000)*8)) 
    old_in=$dev_in 
    old_out=$dev_out 
    echo -e "/e[1;32mIn:$dif_in kb/s Out:$dif_out kb/s/e[0m" 
done

 用perl写了个,可以输出所有网卡的流量,写的很糙,格式输出不好看

#!/usr/bin/perl -w 
use strict; 
my $dev_file = '/proc/net/dev'; 
my $time = 2; 
if(!open ETH_DEV,'<',$dev_file) {die "Cannot open $dev_file/n";} 
 
sub get_dev_info{ 
    my @dev_info; 
    while(<ETH_DEV>){ 
        if(/[0-9]+/){ 
            chomp; 
            my @line = split(/:/); 
            my $dev = $line[0]; 
            @line = split(//s+/,$line[1]); 
            [email protected]_info, ($dev,$line[1],$line[9]); 
        } 
    } 
    seek(ETH_DEV,0,0); 
    return @dev_info; 
} 
my @dev_info_old = get_dev_info; 
while(1){ 
    sleep $time; 
    my $i = 0; 
    #my $dev_sum = 0; 
    my @dev_info_new = get_dev_info; 
    my @result; 
    foreach  (@dev_info_new){ 
        $i++; 
        if($i%3==1){ 
    #       $dev_sum++; 
            my $diff_in = ($dev_info_new[$i]-$dev_info_old[$i])/$time; 
            my $diff_out = ($dev_info_new[$i+1]-$dev_info_old[$i+1])/$time; 
            push @result, ($_."/t","In: ".$diff_in."byte/s/t","Out: ".$diff_out."byte/s/t"); 
        } 
    } 
    @dev_info_old = @dev_info_new; 
#   print "DEVICE/tIN/tOUT/t"x$dev_sum."/n"; 
    print "@result"."/n"; 
} 
close ETH_DEV;

 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/2485.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论