Perl Cookbook

Perl CookbookSearch this book
Previous: 8.17. Testing a File for TrustworthinessChapter 8
File Contents
Next: 8.19. Program: tctee

8.18. Program: tailwtmp

Every time a user logs into or out of a Unix system, a record is added to the wtmp file. You can't use the normal tail program on it because it's in binary format. The tailwtmp program in Example 8.7 knows the format of the binary file and shows every new record as it appears. You'll have to adjust the pack format for your own system.

Example 8.7: tailwtmp

# tailwtmp - watch for logins and logouts; 
# uses linux utmp structure, from utmp(5)
$typedef = 's x2 i A12 A4 l A8 A16 l';
$sizeof = length pack($typedef, () );
use IO::File;
open(WTMP, '/var/log/wtmp') or die "can't open /var/log/wtmp: $!";
seek(WTMP, 0, SEEK_END);
for (;;) { 
        while (read(WTMP, $buffer, $sizeof) == $sizeof) {
        ($type, $pid,  $line, $id, $time, $user, $host, $addr) 
            = unpack($typedef, $buffer);
        next unless $user && ord($user) && $time;
        printf "%1d %-8s %-12s %2s %-24s %-16s %5d %08x\n", 
    for ($size = -s WTMP; $size == -s WTMP; sleep 1) {}

Previous: 8.17. Testing a File for TrustworthinessPerl CookbookNext: 8.19. Program: tctee
8.17. Testing a File for TrustworthinessBook Index8.19. Program: tctee