Login/Logout Hooks in OS X

From AFP548 Wiki
Jump to navigation Jump to search

This article will describe Login and Logout hooks and how to create them.

Create Log In/Out Hook

Before proceeding, note that if you do not have a password, you will need to create a password on your account for this to work.

  1. Open Terminal (Applications/Utilities).
  2. In the Terminal window, for Log In Hooks type
    sudo defaults write com.apple.loginwindow LoginHook /path/to/script
    Where /path/to/script is the full path to the script that you want to execute when a user logs in—it doesn't have to be in the user's Home directory.
  3. In the Terminal window, for Log Out Hooks type
    sudo defaults write com.apple.loginwindow LogoutHook /path/to/script
    Where /path/to/script is the full path to the script that you want to execute when a user logs in—it doesn't have to be in the user's Home directory.
  4. This modifies the /var/root/Library/Preferences/com.apple.loginwindow file.
  5. Type your password at the prompt, then press Return.

Remove Log In/Out Hook

Before proceeding, note that if you do not have a password, you will need to create a password on your account for this to work.

  1. Open Terminal (Applications/Utilities).
  2. In the Terminal window, for Log In Hooks type
    sudo defaults delete com.apple.loginwindow LoginHook /path/to/script
    Where /path/to/script is the full path to the script that you want to execute when a user logs in—it doesn't have to be in the user's Home directory.
  3. In the Terminal window, for Log Out Hooks type
    sudo defaults delete com.apple.loginwindow LogoutHook /path/to/script
    Where /path/to/script is the full path to the script that you want to execute when a user logs in—it doesn't have to be in the user's Home directory.
  4. This modifies the /var/root/Library/Preferences/com.apple.loginwindow file.
  5. Type your password at the prompt, then press Return.

Examples

Clear Home Directory on Log Out

This script is called clrlogout.sh used in a Lab and deletes all user account folders that are not named "admin".

#!/bin/bash
if [ $1 = "admin" ]
    then exit 0
fi

#Deletes the user account and its local home directory
dscl . -delete /Users/$1 #deletes the user from System Preferences
rm -R /Users/$1 #deletes the user's local home directory

exit 0

This script can be amended to not delete other user home directories as well. This script is placed in the folder /Library/Scripts/Company. When applying it as a logout hook, type the command in Terminal:

sudo defaults write com.apple.loginwindow LoginHook /Library/Scripts/Company/clrlogout.sh

References