2

I'm looking for a way in which I can force accounts left logged on to my Mac to auto logoff after a period of inactivity.

There is a setting built in to the operating system (Lion), that does this, but it applies to all users, and I only want to do this with certain accounts.

On Windows, I could use gpedit to force the users to use a screensaver that logs off the users. Is there something similar that I can do on Mac OS X Lion?

p.s. I'm the sole administrator on the system.

Chenmunka
  • 3,264

1 Answers1

3

I've figured out a way of doing this, it's a bit of a hack using shell scripts, cron and sudo, but it seems to work pretty well.

First, create a shell script /bin/usertimeout owned by root, chmod it to 755, and paste the following content into the file

#!/bin/bash

# Timeout is the number of seconds a login session can be idle before it is
# automatically logged out.
timeout=3600

if [ $(stat -f %u /dev/console) == $UID ]
then
  if [ -e /tmp/backgroundUserLogout.$UID ]
  then
    rm /tmp/backgroundUserLogout.$UID
  fi
else
  if [ ! -e /tmp/backgroundUserLogout.$UID ]
  then
    touch /tmp/backgroundUserLogout.$UID
  else
    if [ $(( `date +%s` - `stat -f %m /tmp/backgroundUserLogout.$UID || printf 0` )) -ge $(( $timeout )) ]
    then
      rm /tmp/backgroundUserLogout.$UID
      sudo /sbin/killuser
    fi
  fi
fi

Next, create a file /sbin/killuser, owned by root, chmod it to 755 and paste in the following content

#!/bin/bash
#
# Logs out the user calling this script   

# Get the PID of the loginwindow process for the user executing this
pid=`ps -Axjc | grep ^$SUDO_USER | grep loginwindow | cut -c 14-20 | tr -d /\ /` 

# If the PID appears to be valid, kill the process
if [ $pid -gt 0 2>/dev/null ]
then
  kill -9 $pid
fi

Next add a crontab entry for each user that you want to be auto logged out. This would be a pain if you wanted all users to be affected, but in my case, I only require a small number of users to be logged out on idle.

# Crontab for user that has to be autologged out
* * * * * /bin/usertimeout

Note that the example above runs every minute, depending on the idle time you allow, you might want to increase this to a more suitable frequency (e.g. every 15 mins using */15 * * * * /bin/usertimeout)

Now a simple mod to the sudoers file using visudo and you're good to go.

%users          ALL=(ALL) NOPASSWD: /sbin/killuser