This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Perl hacks for monitoring bandwidth

Since the hackers forum is closed, I'm posting this here...

I've written a perl script for ASL 3 / 5 to monitor our bandwidth usage as I wasn't happy with just the MRTG graphs.
(and I was too lazy to look into SNMP right now)

Barry

Code:

#!/usr/bin/perl -w
#prints time and bandwidth statistics (in kilobits)

$interval = 5;        #seconds

$|++;   #turns off output buffering


#open (LOGFILE, ">net-bandwidth.log") || die "Can't open log: $!.\n";
 
sub getpkt {
        open DEV,"/proc/net/dev";
        while() {
                if(/eth0/) {
                        @line=split(/:|\s+/);
                        close DEV;
                        return $line[2] ."\t". $line[10];
                }
        }
        close DEV;
}
 
($inpkts,$outpkts) = split("\t", getpkt());
 
 
while(1){
        sleep $interval;
 
        ($inpkts2,$outpkts2) = split("\t", getpkt());
 
        #in
        $inbw = 8*(($inpkts2-$inpkts)/$interval)/1024;
        #out
        $outbw= 8*(($outpkts2-$outpkts)/$interval)/1024;
 
        #max
        $max = ($inbw > $outbw) ? $inbw : $outbw;
 
        #printf LOGFILE "%d\t%d\t%d\t%d\n", time(), $inbw, $outbw, $max;

        printf STDOUT "%d\t%d\t%d\t%d\n", time(), $inbw, $outbw, $max;

        $inpkts = $inpkts2;  
        $outpkts = $outpkts2;
}



This thread was automatically locked due to age.