User Time Logged In

A lab I sometimes do computer work for asked for a mechanism to account how long each user spends logged in on some *nix (Linux and ancient Solaris) boxes. I don’t know of a “proper” solution, so I did things the UNIX way: I wrote a stupid little awk script that parses the output of last -R to get a minute total. This isn’t a terribly clean or safe script, but it does “just enough” input sanitizing, and seems to work. Some (Linux) boxes I have access to appear to clear/archive/rotate wtmp on boot, so it doesn’t help on those.
Does anyone know of a better way to do this? Is there some utility I’m forgetting? Is this script dangerous in some way I’m not thinking of? Script follows:

#!/bin/sh
last -R | 
awk '
{
	user=$1;
	uselength=$9;
	
#	Check line format
	if (NF != 9) {
	print "Line " NR " discarded, " NF " entries. (Reboot messages, etc.)"
	}
	else if( $NF == "in"){
	print "Line " NR " discarded, still logged in."
	}
	else{
	
	logins[user]++;
# These times are (Days+Hours:Minutes)
	parsedtime=0;
	gsub("[()]","",uselength);
	split(uselength, sptime, "[+:]");
	parsedtime+=sptime[1]*24*60;
	parsedtime+=sptime[2]*60;
	parsedtime+=sptime[3];
	logintime[user]+=parsedtime;
	}
}
	
END {
	for (i in logins) {
		print i " Logged in " logins[i] " times, for a total of " logintime[i] " minutes";
	}
}'
This entry was posted in Computers, DIY, General, OldBlog. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *