Skip to content

Instantly share code, notes, and snippets.

@mschmitt
Created February 20, 2013 20:54
Show Gist options
  • Save mschmitt/4999520 to your computer and use it in GitHub Desktop.
Save mschmitt/4999520 to your computer and use it in GitHub Desktop.
Playing with utmp(5).
#!/usr/bin/perl -w
use strict;
use diagnostics;
use POSIX;
use User::Utmp qw(:constants);
my $idle_threshold = 1800; # seconds
while (my $utent = User::Utmp::getutent()){
# Skip irrelevant utmp entries that are not interactive sessions
my $uttype = $utent->{'ut_type'};
next unless (USER_PROCESS == $uttype);
my $utline = $utent->{'ut_line'};
my $utuser = $utent->{'ut_user'};
my $utpid = $utent->{'ut_pid'};
my $utipad = $utent->{'ut_addr'};
# Procedure from procps/w.c to get idle time:
# 1) Get atime from terminal device node
# 2) Substract from current time
# 3) ???
# 4) Profit!
my $tty = sprintf("/dev/%s", $utline);
my $atime = (stat($tty))[8];
my $idle = time() - $atime;
my $treatment = 'left_alone';
if ($idle > $idle_threshold){
kill SIGKILL, $utpid;
$treatment = 'killed';
}
printf "tty=%s, pid=%s, user=%s, host=%s, idle=%s, treatment=$treatment\n",
$utline, $utpid, $utuser, join('.',unpack('C4', $utipad)), $idle, $treatment;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment