File: linux_stats.pl

package info (click to toggle)
mrtg 2.9.17-4
  • links: PTS
  • area: main
  • in suites: woody
  • size: 5,140 kB
  • ctags: 1,517
  • sloc: perl: 22,688; ansic: 3,536; sh: 1,309; makefile: 319; php: 227; awk: 213; csh: 49; exp: 16
file content (76 lines) | stat: -rw-r--r-- 2,332 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/perl -Tw
####################################################################
#  linux_stats.pl     1.0            Mike Machado                  #
#                                    mike@innercite.com            #
#                                    2000-07-19                    #
#                                                                  #
#  Script to read traffic stats off linux 2.2 and greater systems  #
#                                                                  #
####################################################################
use strict;



#### Options ####
my $uptimeprog = '/usr/bin/uptime';	# Set to program to give system uptime
my $hostnameprog = '/bin/hostname';	# Set to program to give system hostname
my $defaultinterface = 'eth0';		# Set to default interface
my $defaultstatfile = '/proc/net/dev';	# Set to traffic stats file location


##### Nothing below here should have to be changed #####

if (@ARGV && $ARGV[0] eq '-h') {
	print "Usage: linux_stats.pl [interface] [stats file]\n";
	print "\tIf left blank 'eth0' and '/proc/net/dev' are used\n";
	print "\tInterface of 'ALL' will total all interface traffic, excluding lo\n";
	exit;
}

my $interface = shift || $defaultinterface;
my $statfile = shift || $defaultstatfile;

# Clear path and get uptime
delete $ENV{PATH};
delete $ENV{BASH_ENV};
my $uptime = `$uptimeprog`;
chomp($uptime);
my $hostname = `$hostnameprog`;
chomp($hostname);

my ($in, $out, $found);
open(STATS, $statfile) || die "Cannot open $statfile: $!\n";
while (<STATS>) {
	my $line = $_;
	chomp($line);
	if (uc($interface) eq 'ALL') {
		if ($line =~ /^\s+(.*):\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+$/) {
			next if $1 eq 'lo';
			$in += $2;
			$out += $3;
			$found++;
		}
	} else {
		if ($line =~ /^\s+$interface:\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+$/) {
			$in = $1;
			$out = $2;
			$found = 1;
			last;
		}
	}
}
close(STATS);

if (!$found) {
	print "0\n0\n$uptime\n$hostname: Unknown Interface: $interface\n";
} else {
	print "$in\n$out\n$uptime\n$hostname: Interface: $interface";
	if (uc($interface) eq 'ALL') {
		print " (counted $found interface";
		if ($found > 1) {
			print "s";
		}
		print ")";
	}
	print "\n";
}