#!/usr/bin/perl # # Name : Matthew Reeves # # Displays summary information for a single username using output from last cmd # #use diagnostics; use warnings; use strict; use feature ":5.10"; #if check to verify if exactly 1 command line argument was provided, if 0 or #more than 1 were provided, prints usage statement if ($ARGV[0] ~~ undef || $ARGV[1]) { print "\nUsage: $0 \n\n"; exit; } #initializes variables to be used in program my $input = $ARGV[0]; my $full_input = $input; my @array = `last`; my @target; my $count = 1; my $hours = 0; my $minutes = 0; #checks length of input username, if longer than 8 characters, #truncates input to match length of username in last's output if (length $input > 8) { $input = substr ($input, 0, 8); } #walks through the whole output from running last, then, if input #is found, push that whole line into a new array, @target, and then #print line to screen to display all unique sessions for username. foreach my $line (@array) { if ($line =~ /\b$input\b/) { #prints label for upcoming output on first trigger of #if statement only print "\nHere is a listing of logins for $full_input:\n\n" if $count ~~ 1; push(@target, $line); printf("%3d. $line", $count); $count++; } } #prints to screen statement identifying summary to be output below print "\nHere is a summary of the time spent on the system for $full_input:\n\n"; #prints to screen full, untruncated input username print "$full_input\n"; #prints the total number of logged in sessions my $logons = @target; print "$logons\n"; #this loop uses regular expressions to scrape the hours, minutes, and #(if applicable) days the username was logged in using grouping with #backreferencing to identify and separate the values. When the loop #proccesses a session that is not currently logged in, it adds the #number of hours to the running total stored in $hours, and likewise for #the minutes. If a days value is found, the number of days are converted #to hours, and added to the scalar $hours as well. foreach my $session (@target) { if ($session =~ /\((\d)*\+*(\d\d):(\d\d)\)/) { $hours+=$2; $minutes+=$3; $hours += $1*24 if ($1); } } #section accounts for minute values greater than 59 minutes, and #will convert each 60 minute interval to 1 hour, and adjust $hours and #$minutes accordingly $hours += int($minutes/60); $minutes = $minutes % 60; #print formatted number of hours and minutes logged in to the screen printf ("%02d:%02d\n", $hours, $minutes); say "";