I开发者_运维问答 would like to know how to log the login and logout of a user : it would be a mean to measure how much time someone has been connected in a month so far.
I know it's possible to use the command "last". But this command is based on a file that has a r/w permission for the user, hence the possibility to change these data. I would like to log these data over two months.
Why would I like to do that ? In fact, I would like to prevent a normal user to use a computer (in graphical mode mainly) more than an hour a day - except week-ends, and 10 hours in total a week.
Cedric
(System used : kubuntu,/ Programming language : bash script)
Here's a Perl script which summarises the content printed by last
. It's based on an example from the book Running Linux, cleaned up for readability and corrected to work on a modern machine (the format of last's
output seems to have changed since the original was written). Save the code to a file, and you can then run it by piping the output of last
to it.
#!/usr/bin/perl
# logintime.pl - Summarise amount of time a user is logged in.
# Usage: last | perl logintime.pl
use strict;
use warnings;
my %hours;
my %minutes;
my %logins;
# While we have input...
while ( <> ) {
# Extract the username and login time...
if ( my ($username, $hrs, $mins) = /^(\S+).*\((\d+):(\d+)\)/ ) {
# Increment total hours, minutes, and logins
$hours{$username} += $hrs;
$minutes{$username} += $mins;
$logins{$username}++;
}
}
# For each unique user...
foreach my $user ( sort keys %hours ) {
# Calculate the total hours and minutes...
$hours{$user} += int($minutes{$user} / 60);
$minutes{$user} %= 60;
# Print the information for this user...
print "User $user, total login time ";
printf "%02d:%02d, ", $hours{$user}, $minutes{$user};
print "total logins $logins{$user}.\n";
}
Not quite what you're looking for, but this article shows how to restrict a user from only being able to login during the specified time.
精彩评论