summaryrefslogtreecommitdiff
path: root/scripts/count_pf.perl5
blob: 6b87f78a386a3564bbf4e8d1696b7c17f6769bb3 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/local/bin/perl
#
# count_pf.perl5 -- run lsof in repeat mode and count processes and
#		    files

sub interrupt { print "\n"; exit 0; }

$RPT = 15;				# lsof repeat time

# Set path to lsof.

if (($LSOF = &isexec("../lsof")) eq "") {	# Try .. first
    if (($LSOF = &isexec("lsof")) eq "") {	# Then try . and $PATH
	print "can't execute $LSOF\n"; exit 1
    }
}

# Read lsof -nPF0 output repeatedly from a pipe.

$| = 1;					# unbuffer output
$SIG{'INT'} = 'interrupt';		# catch interrupt
$proc = $files = $tcp = $udp = 0;
$progress="/";
open(P, "$LSOF -nPF0 -r $RPT|") || die "can't open pipe to $LSOF\n";

LSOF_LINE:

while (<P>) {
    chop;
    if (/^m/) {

    # A marker line signals the end of an lsof repetition.

	printf "%s  Processes: %5d,  Files: %6d,  TCP: %6d, UDP: %6d\r",
	    $progress, $proc, $files, $tcp, $udp;
	$proc = $files = $tcp = $udp = 0;
	if ($progress eq "/") { $progress = "\\"; } else { $progress = "/"; }
	next LSOF_LINE;
    }
    if (/^p/) {

    # Count process.

	$proc++;
	next LSOF_LINE;
    }
    if (/^f/) {

    # Count files.

	$files++;
	@F = split("\0", $_, 999);
	foreach $i (0 .. ($#F - 1)) {

	# Search for protocol field.

	    if ($F[$i] =~ /^P(.*)/) {

	    # Count instances of TCP and UDP protocols.

		if ($1 eq "TCP") { $tcp++; }
		elsif ($1 eq "UDP") { $udp++; }
		next LSOF_LINE;
	    }
	}
    }
}


## isexec($path) -- is $path executable
#
# $path   = absolute or relative path to file to test for executabiity.
#	    Paths that begin with neither '/' nor '.' that arent't found as
#	    simple references are also tested with the path prefixes of the
#	    PATH environment variable.  

sub
isexec {
    my ($path) = @_;
    my ($i, @P, $PATH);

    $path =~ s/^\s+|\s+$//g;
    if ($path eq "") { return(""); }
    if (($path =~ m#^[\/\.]#)) {
	if (-x $path) { return($path); }
	return("");
    }
    $PATH = $ENV{PATH};
    @P = split(":", $PATH);
    for ($i = 0; $i <= $#P; $i++) {
	if (-x "$P[$i]/$path") { return("$P[$i]/$path"); }
    }
    return("");
}