start page | rating of books | rating of authors | reviews | copyrights

Perl Cookbook

Perl CookbookSearch this book
Previous: 8.19. Program: tctee Chapter 8
File Contents
Next: 9. Directories
 

8.20. Program: laston

When you log in to a Unix system, it tells you when you last logged in. That information is stored in a binary file called lastlog . Each user has their own record; UID 8 is at record 8, UID 239 at record 239, and so on. To find out when a given user last logged in, convert their login name to a number, seek to their record in that file, read, and unpack. Doing so with shell tools is very hard, but it's very easy with the laston program. Here's an example:

% laston gnat 



gnat  UID 314 at Mon May 25 08:32:52 1998 on ttyp0 from below.perl.com



The program in Example 8.9 is much newer than the tctee program in Example 8.8 , but it's less portable. It uses the Linux binary layout of the lastlog file. You'll have to change this for other systems.

Example 8.9: laston

#!/usr/bin/perl # laston - find out when given user last logged on use User::pwent; use IO::Seekable qw(SEEK_SET);  open (LASTLOG, "/var/log/lastlog") or die "can't open /usr/adm/lastlog: $!";  $typedef = 'L A12 A16';  # linux fmt; sunos is "L A8 A16" $sizeof  = length(pack($typedef, ()));  for $user (@ARGV) {     $U = ($user =~ /^\d+$/) ? getpwuid($user) : getpwnam($user);     unless ($U) { warn "no such uid $user\n"; next; }     seek(LASTLOG, $U->uid * $sizeof, SEEK_SET) or die "seek failed: $!";     read(LASTLOG, $buffer, $sizeof) == $sizeof or next;     ($time, $line, $host) = unpack($typedef, $buffer);     printf "%-8s UID %5d %s%s%s\n", $U->name, $U->uid,           $time ? ("at " . localtime($time)) : "never logged in",           $line && " on $line",            $host && " from $host";





 } 


Previous: 8.19. Program: tctee Perl Cookbook Next: 9. Directories
8.19. Program: tctee Book Index 9. Directories