LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Logged in users (https://www.linuxquestions.org/questions/linux-newbie-8/logged-in-users-596502/)

xlordt 11-01-2007 09:51 PM

Logged in users
 
How do I write a shell script to give me all users that have not logged in, in a certain time?

matthewg42 11-01-2007 09:56 PM

You can see the last login times of users with the last command. You could call that command and process the output somehow.

A more sophisticated (but ultimately probably an easier) approach is to parse the wtmp directly. There are both perl and python modules for doing this.

xlordt 11-01-2007 10:07 PM

Quote:

Originally Posted by matthewg42 (Post 2945243)
You can see the last login times of users with the last command. You could call that command and process the output somehow.

A more sophisticated (but ultimately probably an easier) approach is to parse the wtmp directly. There are both perl and python modules for doing this.

Ya, I have checked out the last command, but it only allows me to input an up to date. and not a from and to date.. if you know what I mean. I guess I will have to code something.

matthewg42 11-01-2007 10:54 PM

Yeah. I just installed the perl Sys::Utmp module, assuming it would also read wtmp, but it seems not.

The utmp/wtmp records are fixed size, so you can unpack them, but the structure differs on 64 and 32 bit systems, so you will have to cope with that.

Here's something I knocked up which you can probably modify to suit your needs:
Code:

#!/usr/bin/perl

use strict;
use warnings;
use POSIX;

open(WTMP, "</var/log/wtmp") || die "cannot open wtmp : $!\n";

my $utmp_size = 384;
my $rec;
my %last_times;
while(read_utmp_rec(\$rec))
{
        my ($typ, $pid, $line, $id, $user, $host,
                $exit_status, $session, $tsec, $tmsec, undef) =
                unpack("l l A32 A4 A32 A256 a4 l l l a", $rec);

        # we are only interested in record type 7 - logins
        next unless ($typ == 7);
        $user =~ s/\s+$//;

        if (defined($last_times{$user})) {
                if ($last_times{$user} > $tsec) {
                        $last_times{$user} = $tsec;
                }
        }
        else {
                $last_times{$user} = $tsec;
        }
}

foreach my $user (sort keys %last_times) {
        printf("last login for user %-8s was %4d mins ago: %s",
                $user,
                (time - $last_times{$user}) / 60,
                ctime($last_times{$user}));
}

sub read_utmp_rec {
        my $recref = shift;
        my $bytes_read = sysread(WTMP, $$recref, $utmp_size);
        if ($bytes_read != $utmp_size) {
                return 0;
        }
        else {
                return 1;
        }
}



All times are GMT -5. The time now is 09:42 PM.