Create a login/logout tracking log file for all users

Aug 18, '06 07:30:02AM

Contributed by: regulus

I have a Mac that I share with my kids. I've given each of them their own account and use parental controls to control what they can access. This gives me a lot of control, but does not tell me everything I want to know. I was also curious about their usage habits, such as what time of day they login and how long they typically are on the computer, so I needed a way to track that data.

After reading about login hooks in OS X, and doing a little more research on the web, I came up with a few simple scripts that can be run at login and logout to solve my problem. With these scripts, any time anyone logs into or out of the computer, a log entry will be created. If you keep your log file in the /var/log directory, then you can easily view the file using the Console application.

So here's how I did it.

  1. Create the login and logout scripts as follows. Here's the login script:
    # login script
    timestamp=`date ''+%m-%d-%Y_%H:%M:%S''`
    echo $username," "$timestamp," "$computer," login" >> "$logfile"
    And here's the logout script:
    # logout script
    timestamp=`date ''+%m-%d-%Y_%H:%M:%S''`
    echo $username," "$timestamp," "$computer," logout" >> "$logfile"
  2. Save the scripts in /usr/local/bin as loginscript and logoutscript, respectively.

  3. Run the following Terminal commands to give the scripts execute permissions:
     $ sudo chown a+x /usr/local/bin/loginscript
     $ sudo chown a+x /usr/local/bin/logoutscript
  4. Run the following two Terminal commands to create the login and logout hooks:
     $ sudo defaults write \
       LoginHook /usr/local/bin/loginscript 
     $ sudo defaults write \
       LogoutHook /usr/local/bin/logoutscript
That's it! Now you have a way to see everyone's login and logout times. When you want to view the log, just open the Console application, go to the /var/log section, and click on the usertracking.log file. The first time somebody logs in or out the log file will be created.

To remove these changes, type the following commands in Terminal:
 $ sudo defaults delete LoginHook
 $ sudo defaults delete LogoutHook
 $ sudo rm /usr/local/bin/loginscript
 $ sudo rm /usr/local/bin/logoutscript
 $ sudo rm /var/log/usertracking.log
You can also track who logs into your computer via file sharing over your network, as explained in this hint. You can also completely disable the ability for guests to login via file sharing, as explained in this hint.

Good luck!

Comments (20)

Mac OS X Hints