Piddle: a Perl idleout program

I've never been happy with idleout. It is a shell script, so you can modify it for your own needs, but it lacks many features that people want, and can often be wrong about whether or not a user truly is idle. It is also not particularly easy to modify for complex uses.

A better program is nidleout by John Dubois. This has many more features, and is far less apt to be wrong about idleness, but it still has problems. For one thing, it's written as a ksh script, and it pushes the capabilities of ksh fairly hard, so it too isn't all that easy to modify. Further, it (by design) simply ignores certain processes that it cannot be sure about, and that list includes console X sessions.

Linux has "autolog".

There are also commercial solutions. Computronics Logmon is product that doesn't have the limitations of idleout and offers extensive configuration capability.

So, I started thinking about how I could really tell if someone was idle, and it struck me that /etc/crash could give me most of what I needed. The resulting program is presented here. It isn't perfect, but it seems to have some capabilities lacking in other methods, so it might work for you.

Diller Ryan noted this bug: I tried your PIDDLE.PL program. I don't think you can do anything about it, but there seems to be a problem in the perl library popen code. After running for a day, the program apparently used my quota of processes. 'ps' displayed a huge list of zombies, which I believe were the residue of your periodic queries. It seems like there should be a 'wait' in the the library code. Have you noticed this before? I doubt it's anything to do with the spawning of "ps" and "crash". A zombie is the result of a parent process that dies before its children, and piddle doesn't die. Rather I suspect it has to do with the ordering of the kills, but it's still something that may need work.

This uses a configuration file (actually, it can use several different configuration files, but we'll get to that later). Here's a sample file:

# piddle configuration file
# root on console (secure room) gets 60 minutes
root:tty01=60
root:tty02=60
root:tty03=60
root:tty04=60
# root on any other terminal only gets 10 minutes
root:*=10
# tty2a is in open area, 10 minutes only
*:tty2a=10
# tony gets to stay in a long time
tony:*=9999
# otherwise, anybody else gets 15 minutes
*:*=15
# exit after 8 hours
# this is so you can have different rules files for different
# times of days, days of the week, etc.
RUNTIME=480
# processes that need to be ignored because they tick even when idle
TICKS=xdt3_binary
TICKS=Xsco
# using long process listing, bypass users running IGNORE
IGNORE=checks
IGNORE=cash -d update
 

You can probably figure most of this out by yourself, but some explanation may be needed for some of it.

TICKS, for example, are programs that will have "activity" in /etc/crash even when the user really is idle. A good example of that is a user running the gui on the console: Xsco and xdt3_binary will appear to be busy even when the user really isn't. By setting TICKS lines equal to these programs, we can idle those users out (note that nidleout handles these "event driven" programs by ignoring them entirely, and that idleout sees such users as idle even when they are not).

IGNORE is for the case when you definitely do not want to kill a user running a particular process. The string argument will be compared to the long argument from ps, not the command argument (note the difference between

ps -o pid= -o args=
 

and

ps -o pid= -o comm=
 

if that confuses you).

RUNTIME is so that you can have different rules for different times of day, different days of the week, etc. Just fire "piddle"'s off from crontab, giving different configuration files as arguments, and setting RUNTIME so that one exits before the other starts.

Piddle is designed so that you can test it without actually affecting any user. If the debug level is set to "1" (as it is by default), debugging output will be written to /tmp/piddle.debug, and this will include information about the users and processes that would be killed if debug were set to "2" or were not set at all.

One note: the accuracy is rather granular: someone supposed to get 15 minutes of grace may get close to 30 under some conditions. I haven't felt that is important.

Please do test this before turning it loose. If you find improvements that could be made, please report them to me.


#!/usr/bin/perl5
#
# (c) November 1998 A.P. Lawrence http://www.aplawrence.com
# An idleout program that uses /etc/crash to determine actual idle
# state.  Because of this, it has no problem at all with 
# users using "pg", X-windows users, programs running in
# background, etc.
#
# This is not designed to be rigorusly accurate: if a user
# is supposed to be idled out after 15 minutes, it could take
# a half hour before this determines they truly are idle.
#
# Other notes:
# A defaults file can be specified on the command line.  This
# file can contain:
# RUNTIME=480
# which means that the program should run for only 480
# minutes.  If RUNTIME=9999, it should run forever
#
# TICKS=
# These would be programs (like xdt3_binary an Xsco) that will have
# "activity" even when a user really is idle.  Listing these
# as TICKS (multiple TICKS entries each on new line) means
# that user will get idled out if these are the only processes
# with activity.  On the other hand, if you don't want
# your console X-session to get logged out, don't enter any TICKS
# and then the activity of Xsco etc will keep this looking not
# idle.
# ->IGNORE=
# This again can have multiple occurences.  Each of these is a
# text string which identifies a program which, if being used,
# the user will NOT be idled out no matter what.  This shouldn't
# be necessary as far as I can tell, but it is extra assurance.
# 
# Other entries take the form of "user:terminal=30"; see below for
# examples
#
# set defaults
# rules file defaults to /etc/default/idlehands or is passed
# on command line: piddle /mydir/mydefaults
#
#
# this is a sample rules file:
#
#  		# root on console (secure room) gets 60 minutes
#  		root:tty01=60
#  		root:tty02=60
#  		root:tty03=60
#  		root:tty04=60
#  		# root on any other terminal only gets 10 minutes
#  		root:*=10
#  		# tty2a is in open area, 10 minutes only
#  		*:tty2a=10
#  		# tony gets to stay in a long time
#  		tony:*=9999
#  		# otherwise, anybody else gets 15 minutes
#  		*:*=15
#  		# exit after 8 hours
#  		# this is so you can have different rules files for different
#  		# times of days, days of the week, etc.
#  		RUNTIME=480
#  		# processes that need to be skipped 'cause they tick
#             TICKS=xdt3_binary
#             TICKS=Xsco
#             # using long process listing, ignore strings with IGNORE
#             IGNORE=checks
# 
use IPC::Open2;
$rules=$ARGV[0] || "/etc/default/idlehands";
# set certain rules for case of no rules file:
# any user on any terminal is 15 minutes
#
$rule{"*:*"}=15;
#
#
# run forever:
#
$rule{"RUNTIME"}=9999;
#
# no ticks:
#
$rule{"TICKS"}="";
# 
# debug state: change to 0 when happy
#
$debug=1;
# change to $debug=1 for just testing- no actual kills
# change to $debug=2 for actual kills
# change to $debug=3 for just testing- no actual kills, extended information
#
##debug
if ($debug) {
  open(DEBUG,">>/tmp/piddle.debug");
  select DEBUG;
  $|=1;
  $date=qx(/bin/date);
  print DEBUG "Piddle: (c) November 1998 A.P. Lawrence: tony\@aplawrence.com\n";
  print DEBUG "http://www.aplawrence.com\n";
  print DEBUG "Restarting $date using Rules $rules\n";
  print DEBUG "Debug level is $debug\n";
}
##debug end
open(RULES,$rules) or print "No $rules file; defaulting..\n";
while (<RULES>) {
  chomp;
  next if /^#/;
  ($userterminal,$minutes)=split /=/;
  $rule{$userterminal}=$minutes;
  if (/^TICKS/) {
    $ticks{$minutes}=$minutes;
    }
  if (/^IGNORE/) {
    $ignore{$minutes}=$minutes;
    }
  }
##debug
if ($debug) {
  print DEBUG "Rules:\n--------------------\n";
  foreach $i  (sort keys %rule) {
    if ($i eq "TICKS" ) {
      foreach $j (sort keys %ticks) {
        print DEBUG "TICKS $ticks{$j}\n";
        }
    } else {
    if ($i eq "IGNORE" ) {
      foreach $j (sort keys %ignore) {
        print DEBUG "IGNORE $ignore{$j}\n";
        }
      } else {
      print DEBUG "$i $rule{$i}\n";
      }
    }
  }
  print DEBUG  "--------------------\n";
  }
##debug end
#
# what is minimum sleep time?
#
$sleepfor=9999;
foreach $timerule  (keys %rule) {
  next if ($timerule eq "RUNTIME" or $timerule eq "TICKS" or $timerule eq "IGNORE");
  if ($rule{$timerule} < $sleepfor) {
    $sleepfor=$rule{$timerule};
    }
  }
$sleepseconds=60;
$sleepseconds *= $sleepfor;

if ($debug) {
  print DEBUG "Minimum sleep is $sleepfor\n";
  }

# prime data for first pass
getidles();
$now=0;
#
# main loop
while ($now < $rule{"RUNTIME"}) {
  sleep($sleepseconds);
  undef %pass2;
  %pass2=%pass;
  getidles();
  foreach $procid (sort keys %pass) {
   ##debug
   if ($debug and $ticks{$arg{$procid}}) {
     print DEBUG "$procid $arg{$procid} $pids{$procid} ignored\n";
     }
   ##debug end
   next if $ticks{$arg{$procid}};
   $matched=0;
   if ($rule{IGNORE}) {
      $longarg=qx(ps -p $procid -o args=);
      foreach $j (sort keys %ignore) {
        $matched = $longarg=~ m/$ignore{$j}/;
        $userterm=$pids{$procid};
        $idles{$userterm}=0 if $matched;
        ##debug
	if ($debug and $matched) {
	  print DEBUG "matched $matched for $procid $pids{$procid}\n";
          print DEBUG "$userterm idle reset to 0\n";
	  }
        ##debug end
        $matched=0;

        }
     
     }
   unless ("$pass2{$procid}" eq "$pass{$procid}") {
    # reset idle time if had activity
    $userterm=$pids{$procid};
    $idles{$userterm}=0;
    ##debug
    if ($debug) {
        print DEBUG "pass2 $procid $arg{$procid} ($userterm) not idle\n";
        }
     }
    ##debug end
    }

  $now += $sleepfor;
  foreach $userterm (keys %idles) {
    if ($idles{$userterm} >= $uminutes{$userterm}) {
       killer($userterm);
       }
    $idles{$userterm} += $sleepfor;
    
    }
##debug
if ($debug) {
  print DEBUG "=================================\n";
  print DEBUG "Have now run $now of $rule{RUNTIME} minutes\n";
  print DEBUG "=================================\n";
  }
##debug end
if ($rule{RUNTIME}==9999) { $now=0; }

  }
exit 0;

sub getidles {
# open a pipe to "crash"
undef %pass;
open2(\*READCRASH,\*WRITECRASH,"/etc/crash") or die "Oops! What happened to /etc/crash?";
# open a pipe to "w"
open(W,"/usr/bin/w |") or die "Oops! What happened to /usr/bin/w?";
# discard two lines
$head=<W>;
$head=<W>;
# now read the rest of it:
#
while (<W>) {
  ($user,$tty,$login,$idle,$jnk,$min)=unpack("A9 A8 A8 A4 A1 A2",$_);
  $idle=int($idle)*60 + $min;
  # if we haven't seen this person before, we trust "w"
  if ( not $idles{"$user:$tty"}) {
    $idles{"$user:$tty"}=$idle;
    }
  # if "w" says they are idle less than we say, we trust "w"
  if (  $idle < $idles{"$user:$tty"}) {
    $idles{"$user:$tty"}=$idle;
  }
}
close(W);
#
foreach $userterm (keys %idles) {
  ($user,$tty)=split(/:/,$userterm);
  $userminutes=$rule{"$user:$tty"} || $rule{"*:$tty"} || $rule{"$user:*"} || $rule{"*:*"};
##debug
if ($debug) {
   print DEBUG "$user is on $tty idle for $idles{$userterm} of $userminutes\n";
}
##debug end
#
$uminutes{$userterm}=$userminutes;

  open(PS,"/bin/ps -t $tty -o pid= -o comm= |") or die "Oops! What happened to /usr/bin/ps?";
  while (<PS>) {
    chomp;
    s/^\s+//;
    ($pid,$comm)=split / /;
    $cpid="#$pid";
    print WRITECRASH "user $cpid\n";
    while (<READCRASH>) {
        chomp;
        ##debug
        if ($debug == 3) {
         print DEBUG "$_\n";
         }
        ##debug end
        if (/PROCESS TIMES/) { $ptime=$_;}
        if (/u_base/) { $ufiles=$_;}
        last if /SIGNAL/m;
        last if /.* not valid process id/m;
        last if /.* is a zombie process/m;
        last if /Syntax error/m;
    }
    $pass{$pid}="$ufiles $ptime";
    $arg{$pid}=$comm;
    $pids{$pid}=$userterm;
  }
close(PS);
}
print WRITECRASH "quit\n";
close(READCRASH);
close(WRITECRASH);
wait;
##debug
if ($debug) {
  print DEBUG "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
  }
##debug end
}

sub killer {
  $userterm=shift(@_);
  ##debug
  if ($debug) {
    print DEBUG "would kill $userterm...\n";
    foreach $pid (sort keys %pids) {
      if ($pids{$pid} eq $userterm) {
        print DEBUG "would kill pid $pid\n";
        }
      }
  }
 ##debug end
  if (not $debug or $debug == 2 ) {
    foreach $pid (sort reverse keys %pids) {
      if ($pids{$pid} eq $userterm) {
        qx(kill $pid\n);
	##debug
        print DEBUG "kill -15 $pid sent\n";
	##debug end
        }
      }
    sleep 5;
    foreach $pid (sort reverse keys %pids) {
      $stillthere=qx(ps -p $pid -o pid=);
      next if not $stillthere;
      if ($pids{$pid} eq $userterm) {
        qx(kill -9 $pid\n);
	##debug
        print DEBUG "kill -9 $pid sent\n";
	##debug end
        }
      }
    }
}
 


Got something to add? Send me email.





(OLDER) <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> Piddle (inactivity monitor - old SCO Unix)




Increase ad revenue 50-250% with Ezoic


More Articles by

Find me on Google+

© Tony Lawrence



Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us





The danger of computers becoming like humans is not as great as the danger of humans becoming like computers. (Konrad Zuse)

A learning experience is one of those things that say, "You know that thing you just did? Don't do that." (Douglas Adams)








This post tagged: