Linux User Logon Script
Here’s a short script in Perl that checks which users have not logged in over 5 days. I wrote it to run automatically via cron and send emails to users reminding them that their inactivity paste 5 days (for example) will cause their account to be locked and then deleted (e.g. past 10 days). Hope someone finds it useful:
#!/usr/bin/perl
$wtmpx_file_loc = "/var/log/wtmp";
@type=("Empty","Run Lvl","Boot","New Time","Old Time","Init","Login","Normal","Term","Account");
$templ = "l";
$template = "i i A32 A4 A32 A256 i i i2 l4 A20";
# 1 2 3 4 5 6 7 8 9 10 11
$recordsize = length(pack($template,( )));
$records = length(pack($templ,( )));
open(WTMP,$wtmpx_file_loc) or die "Unable to open wtmpx: $!\n";
@users = `egrep -i 'bash' /etc/passwd|awk -F":" '{print \$1}'`;
chomp(@users);
my %user = (
$id => { $lastlog => '' }
);
while (read(WTMP,$record,$recordsize)) {
($ut_type,$ut_pid,$ut_line,$ut_id,$ut_user,$ut_host,$ut_exit,$ut_session,$ut_tv,$ut_addr_v6,$ut_unused)=unpack($template,$record);
if ($ut_user eq "") { next; }
if ($ut_tv > $user{$ut_user}{$lastlog}) {
$user{$ut_user}{$lastlog} = $ut_tv;
}
# print "ut_user=$ut_user ut_host=$ut_host ut_tv=$ut_tv"."\n";
}
#$user{'hfarrell'}{$lastlog} = time() - 24*60*60*5;
$today = time();
foreach $key (@users) {
$diff = $today - $user{$key}{$lastlog};
printf "%-15s - %-25s", $key, scalar localtime($user{$key}{$lastlog});
$days = time() - $user{$key}{$lastlog};
my ($sec, $min, $hour, $day,$month,$year) = (localtime($diff))[0,1,2,3,4,5,6];
if (!defined $user{$key}{$lastlog}) {
print " ** NEVER LOGGED ON";
} elsif ($days > (5*(24*60*60))) {
printf " ** DID NOT LOG IN THE LAST 5 DAYS--OVER BY %d DAY(S)", ($days/(24*60*60));
}
print "\n";
}