Link to home
Start Free TrialLog in
Avatar of PMG76
PMG76Flag for United States of America

asked on

User login summary

I need some help making a program that prints a summary to the screen using the "last" command in Unix.  I need to take the account, terminal, hostname, date , login, logout, and duration (in HH:MM format) fields and output the following information formatted like this:  ACCOUNT = LOGINS = TIME.  I have some code but I am getting errors.  I'd appreciate some help.
Avatar of PMG76
PMG76
Flag of United States of America image

ASKER

Here is what I have so far
#!/usr/bin/perl


use warnings;
use strict;


my @capture = `last | less`;
my $length = length $ARGV[0];
my $input = $ARGV[0];
my $hours = 0;
my $minutes = 0;
my $c = 0;
my $b = 0;

while ($length >= 9)
        {
        chop ($ARGV[0]);
        $length --;
        }
my $count = 0;
my @array = grep /$ARGV[0]/, @capture;

foreach my $line (@array)
        {
         $a = substr ($line, 0, $length);
        if ($ARGV[0] =~ /$a/)
        {
        $count ++;
        }



($b, $c) = ($line =~ /\b(\d\d\).(\d\d)/);
$hours += $b;
$minutes += $c;
print "$line\n";
}

print "$count\n";
print "$hours $minutes\n";

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Tintin
Tintin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PMG76

ASKER

SO if I wanted to also list the logins for the user where would I do that and what syntax?
Avatar of Tintin
Tintin

If you want to list the login, just add

print;

after

 next unless /^$user/;

Avatar of PMG76

ASKER

Thank you.  One last thing.  How do I assign a number to each logon printed at the beginning of the line?  1, 2, 3 etc?

Thanks so much!
Avatar of PMG76

ASKER

This is the code i need to insert it into BTW.
use warnings;
use strict;


my @capture = `last | less`;
my $length = length $ARGV[0];
my $input = $ARGV[0];
my $hours = 0;
my $minutes = 0;

while ($length >= 9)
	{
	chop ($ARGV[0]);
	$length --;
	}

my $count = 0;
my @array = grep /$ARGV[0]/, @capture;

foreach my $line (@array)
	{
	 $a = substr ($line, 0, $length);
	if ($ARGV[0] =~ /$a/)
	{
	$count ++;
	}
	if ($line =~ /\((\d\d):(\d\d)\)/)
	{$hours += $1;
	$minutes += $2;
	print "$line";
	}
}
$hours += ($minutes-($minutes %60)) / 60;
$minutes = ($minutes % 60);

print "\nHere is a summary of the time spent on the system for: $input\n";
print "$input=$count=$hours:$minutes\n\n";

Open in new window


#!/usr/bin/perl
use strict;

my $user = shift or die "Usage: $0 [user]\n";

open my $last, "/usr/bin/last $user|" or die "Could not run last command $!\n";

my ($logins,$hours,$mins);

while (<$last>) {
  next unless /^$user/;

  $logins++;

  print "$logins $_";

  if (/\((\d\d):(\d\d)\)/) {
    $hours += $1;
    $mins += $2;
  }
}

print "User: $user, logins: $logins, time: $hours hours $mins minutes\n";

Open in new window