Get name of active user in script on Mac OS

3

I have a perl script (this script, to be exact) that logs user activity based on idle time on a MacOS X Snow Leopard System. However, with Fast User Switching enabled, more than one user might be logged in at the same time. I want the script to see the computer as 'idle' if another user is active (i.e. using the GUI) through Fast User Switching.

There are numerous ways to figure out when a user logged in. Finding out when a user last "switched" seems more difficult. My solution so far was to look at /var/log/secure.log, where Fast User Switching events are logged:

tail -200 /var/log/secure.log | grep "User info context values set" | tail -1

However, for users running the perl script that are not Admin, secure.log will not be readable. Are there any alternative ways to find out which user is currently actively logged in, or what the last Fast User Switching event was?

Of course, the problem could be circumvented if I had a method for finding out the idle time for the user running the script only, not the total idle time of the computer I'm currently getting from ioreg. So, I'm open to suggestions there as well.

Thanks!

Michael Goerz

Posted 2010-09-19T18:35:26.093

Reputation: 560

What if I only trigger Fast User Switching (CGSession), but do not actually switch to another user when the login window is shown? And when using Vine Server, multiple users could be active simultaneously. In other words: if you're really only tracking a specific user, then maybe you should indeed find a way to see if that user is truly active, rather than trying to determine if someone else might be active?

– Arjan – 2010-09-19T19:05:52.433

In a wild guess I figured maybe CGSession might have some useful command line options, but no cigar, I guess: strings /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession | grep "^-" – Arjan – 2010-09-19T19:18:08.703

I wouldn't be worried about "multiple users" through VNC sessions. – Michael Goerz – 2010-09-20T01:38:41.077

You're right of course: I either want to find out whether a specific user is logged in and using the GUI at this moment, or get the idle time for that user only, instead of the whole system. – Michael Goerz – 2010-09-20T01:40:21.340

Answers

4

I don't know how to get time since switch, but you can get the currently active user by checking ownership on /dev/console. There's probably a better way in Perl, but the stat command'll do it:

my $user = `stat -f%Su /dev/console`;

Gordon Davisson

Posted 2010-09-19T18:35:26.093

Reputation: 28 538

seems to work perfectly! – Michael Goerz – 2010-09-20T08:24:07.863

Nice! Also, you'll be getting root while the login window of Fast User Switching is shown: while true; do stat -f%Su /dev/console; sleep 2; done – Arjan – 2010-09-20T17:45:42.127