#!/usr/bin/perl -I/HIDDEN_FOR_INFN_SECURITY use Time::HiRes qw ( time alarm sleep ); use Getopt::Long; $| = 1; $interval = 0.5 ;# seconds, float $track = 0; $maxtr = 100; $barlen = 25; $iface = 'eth'; #( $iface = $ARGV[0] ) =~ s/\d+$//; $help = ' Usage: netspeed -i= [OPTIONS] Example: netspeed -i=eth[0-9] -p=10240 -b=12 -d=0.5 -f=/tmp/if_speeds.log -i, --interface=REGEXP Net interface to listen to. -f, --log-file=FILENAME Log speeds to a file. -p, --print-trace=MBITS Trace speeds above the specified limit -d, --delay=SECONDS Refresh every n seconds (float). -b, --bandwidth=MBITS Max speed of interfaces. -u, --upbandwidth=MBITS Max upload speed of interfaces. -h, --help Print this help. '; GetOptions ( 'interface=s' => \$iface, 'file-log=s' => \$logfile, 'print-trace=i' => \$track, 'delay=f' => \$interval, 'bandwidth=f' => \$maxtr, 'upbandwidth=f' => \$maxtrup, 'help' => sub{ print $help; exit; } ); #print "iface: $iface, logfile: $logfile, track: $track, interval: $interval\n"; $maxtrup = $maxtr unless $maxtrup; $track = $track *1024 if $track; unless ($iface) { print $help; exit; } `resize`; $termwidth = $ENV{'COLUMNS'}; $termwidth = 80 unless $termwidth; if ( !$termwidth ) { `resize` =~ /COLUMNS=(\d+)/; $termwidth = $1; } ( $barlen = ( $termwidth - length($iface) - 26 ) / 2 ) =~ s/\..*//g; printf "\n%-".length($iface)."s | %-".(6+3+$barlen)."s | %-".(6+3+$barlen)."s |\n", "if", "Kb/s RX" , "Kb/s TX"; $lastover = time(); #unless ( sleep(0.1) ) { # print "Time::HiRes not found. Interval not float.\n"; # $interval=1; #} while ( 1 ) { sleep($interval); $kbin = $kbout = $pksin = $pksout = 0; open( COUNTERS, " ) { if ( /^.*$iface(.*):\s*(\d+)\s*(\d+)(\s*\d+){6}\s*(\d+)\s*(\d+)(\s*\d+){6}/ ) { $kbin += $2/1024*8; $kbout += $5/1024*8; $pksin += $3; $pksout += $6; } } close(COUNTERS); if (!$kbinold && !$kboutold) { $kbinold = $kbin; $kboutold = $kbout; next; } $kbSin = ( $kbin - $kbinold ) / $interval; $kbSout = ( $kbout - $kboutold ) / $interval; $kbSin = 0 if $kbSin < 0; $kbSout = 0 if $kbSout < 0; $barIN = ''; for ($b=1 ; $b <= ($kbSin/1024/$maxtr*$barlen) ; $b++) { $barIN .= '#'; last if $b >= $barlen; } $barOUT = ''; for ($b=1 ; $b <= ($kbSout/1024/$maxtrup*$barlen) ; $b++) { $barOUT .= '#'; last if $b >= $barlen; } printf "%-".length($iface)."s | %6d #%-${barlen}s# | %6d #%-${barlen}s# |", $iface, $kbSin, $barIN, $kbSout, $barOUT ; $nowtime = localtime ; if ( $track && ( $kbSin >= $track || $kbSout >= $track ) ) { print "\n^^^^ at $nowtime ^^^^\n" ; $nowtime = '^^^^^^^^^^^^^^^^^^^^^^^^' if $lastover+1 >= time(); $lastover = time(); if ( $logfile ) { open( LOG, ">>$logfile" ); printf LOG "$iface: kB Rx: %10d / Tx: %10d - at %s \n", $kbSin, $kbSout, $nowtime; close( LOG ) ; } } else { print "\r"; } $kbinold = $kbin; $kboutold = $kbout; }