Wtmp clean

From Notes

Jump to: navigation, search
 #!/usr/bin/perl
 #**********************************************************************
 # Script   : /site/local/sbin/wtmp-clean.pl
 # Parent   :
 # Children :
 #
 # Author   : Josh Miller
 #
 # Date     : 03/12/07
 # System   : wtmp Maintenance
 #
 # Description : Clean all but the last 90 days of activity from wtmp.
 #  Note: There is no mail function built-in yet.
 #
 # Files : Input -
 #         Output -
 #
 # ------------------------------------------------------------------------------
 
 %molist = (
        "01" => "Jan",
        "02" => "Feb",
        "03" => "Mar",
        "04" => "Apr",
        "05" => "May",
        "06" => "Jun",
        "07" => "Jul",
        "08" => "Aug",
        "09" => "Sep",
        "10" => "Oct",
        "11" => "Nov",
        "12" => "Dec"
 );
 
 # Set length of time to clean in months (ie, leave the last X number of months)
 $threshold = 3 ;
 
 $hostname = `hostname` ;
 
 # Get the date
 $month = `date +%m` ;
 
 chomp ($month) ;
 $curmonth = $molist{$month} ;
 
 $curyear = `date +%Y` ;
 chomp ($curyear) ;
 $prevyear = ($month > $threshold) ? $curyear : ($curyear - 1) ;
 
 $startmonth = $month - $threshold ;
 $prevmonth = ($startmonth > 0) ? $startmonth : (12 + $startmonth) ;
 $prevmonth = ($prevmonth < 10) ? "0" . $prevmonth : $prevmonth ;
 $prevmonth = $molist{$prevmonth} ;
 
 # Get an ASCII version of wtmp
 $status = "creating ASCII version of wtmp\n" ;
 $wtmp = `/usr/sbin/acct/fwtmp < /var/adm/wtmp > /tmp/wtmp` ;
 
 # Save off the current month and the previous 3 months
 #     (designed to run on the 1st)
 $status = "creating new ASCII wtmp\n" ;
 open (WTMP, "/tmp/wtmp") or die "Unable to open /tmp/wtmp: $!\n" ;
 open (NEWWTMP, ">>/tmp/wtmp.new") or die "Unable to open /tmp/wtmp.new: $!\n" ;
 while ( <WTMP> ) {
   if ( /$prevmonth.*$prevyear/ .. eof(WTMP) ) {
     print NEWWTMP $_ ;
   }
 }
 close (WTMP) ;
 close (NEWWTMP) ;
 
 # Convert new saved wtmp back to binary in /var/adm/wtmp
 $status = "converting new ASCII wtmp to binary wtmp\n" ;
 $wtmp = `/usr/lib/acct/fwtmp -ic < /tmp/wtmp.new > /var/adm/wtmp` ;
 
 # Cleanup
 $cleanup = `rm /tmp/wtmp.new` ;
 $cleanup = `rm /tmp/wtmp` ;
 
 exit(0) ;
 
 ## Subroutines ###################################
 
 sub mail() {
   if ( $_[0] ) {
     $status = $_[0] ;
   } else {
     $status = "Critical Error" ;
   }
 open(SENDMAIL, "|/usr/sbin/sendmail -oi -t") or die "Can't open sendmail: $!\n" ;
 print SENDMAIL << "EOF" ;
 From: $hostname <root@$hostname>
 To: root
 Subject: wtmp clean script
 
 Failure $status
 
 Please investigate.
 EOF
 close(SENDMAIL) ;
 }