DaysSinceLastLogin.pl
#!/usr/bin/perl -w
# DaysSinceLastLogin.pl
# Displays the numbers of days since
# a user last logged in in table form.
# - Jim
# Input File Handlers:
$IFile1="lastlog";
$IFile2="/etc/passwd";
# Hash table to store the user's name and last log in.
%users=();
# Save the date as the number of seconds since January 1, 1970.
$DateInSeconds = time();
# Open $IFile1 for reading only.
open (LastLog, '<', $IFile1) or
die ("Unable to open \"$IFile1\" due to error: \"$!\"");
# Open $IFile2 for reading only.
open (Passwd, '<', $IFile2) or
die ("Unable to open \"$IFile2\" due to error: \"$!\"");
# Create a hash table with all the user names as keys.
while (defined ($_ = ) )
{
$user=(split /:/, $_)[0];
# Add the user name as a key.
$users{$user}="";
}
# Go through the lastlog file,
# grab the user names in it and the time last logged in
# if it exists.
while (defined ($_ = ) )
{
# Is the line a user name or the string
# "time_last_login"?
# ^\w+: Line starts with one or more word characters
# followed by a :.
# ^\s*time_last_login Line starts with zero or more spaces followed by
# time_last_login.
if ($_ =~ /^\w+:|^\s*time_last_login/)
{
# If the string is a user, assign
# it as a key. If the string is not
# put it as the value to the key.
if ( $_ =~ /:/ )
{
# Find the user name and remove the : at the end.
$user = substr($_, 0, -2);
}
else
{
# The string is the time_last_login value.
# Save the number into the $users hash table.
# \d+\ means find the number and () save it
# into memory: $1;
$_ =~ /(\d+)/;
# Find the number of days with fraction included.
$DateInDays = ($DateInSeconds - $1)/60/60/24;
# Remove the fraction portion from the variable.
$DateInDays =~ (/(\d+)./);
$users{$user}=$1;
}
}
}
# Print the hash table.
print "The follow users have logged in:\n\n";
print " User ", " Days Since Last Login\n";
foreach $key (sort (keys(%users)))
{
if ( "$users{$key}" ne "" )
{
# Print the user's name and last log in.
printf "%8s %3d\n", $key, $users{$key};
}
else
{
# The user has never logged in.
# Save there name in a list.
@NeverLoggedIn=(@NeverLoggedIn,$key);
}
}
print "\n\n";
print "The follow users have NEVER logged in:\n\n";
foreach (@NeverLoggedIn)
{
print "$_\n";
}
# Close the files opened at the beginning.
close $IFile1;
close $IFile2;