use process accounting to display summary of process, user and tty usage
[sysadmin-cookbook] / recepies / acct / lastcomm-duration.pl
diff --git a/recepies/acct/lastcomm-duration.pl b/recepies/acct/lastcomm-duration.pl
new file mode 100755 (executable)
index 0000000..f0d1dc0
--- /dev/null
@@ -0,0 +1,31 @@
+#!/usr/bin/perl
+
+use warnings;
+use strict;
+
+use YAML;
+
+my $too_long = 0.5; # s
+my $stats;
+
+open(my $lastcomm, '-|', 'lastcomm');
+while(<$lastcomm>) {
+       chomp;
+       if ( m{^(\S+).+?(\S+)\s+(\S+)\s+(\d+\.\d+) secs} ) {
+               my ( $command, $user, $tty, $duration ) = ( $1, $2, $3, $4 );
+               $stats->{command}->{$command} += $duration;
+               $stats->{user}->{$user} += $duration;
+               $stats->{tty}->{$tty} += $duration;
+               print "$_\n" if $duration > $too_long;
+       } else {
+               warn "# $_";
+       }
+}
+
+foreach my $stat ( keys %$stats ) {
+       print "\n$stat:\n";
+       my $counter = $stats->{$stat};
+       foreach my $name ( sort { $counter->{$b} <=> $counter->{$a} } keys %$counter ) {
+               printf "%8.2f %s\n", $counter->{$name}, $name;
+       }
+}