Beyond the good ol' LaunchAgents - 22 - LoginHook and LogoutHook

This is part 22 in the series of “Beyond the good ol' LaunchAgents”, where I try to collect various persistence techniques for macOS. For more background check the introduction.

This method is considered deprecated by Apple, yet it still works.

LoginHooks and LogoutHooks have been widely documented by many people, so this post is mostly for completeness. The official, Apple documentation can be found here: Customizing Login and Logout

LoginHooks and LogoutHooks are executed, well… at logins and logouts just as the name suggest, and they are run as root. They are set in the preferences of the process, and so it’s stored in the file /var/root/Library/Preferences/

We can use the defaults utility to add a hook, like the following:

sudo defaults write LoginHook /path/to/loginscript

Similarly we can install a LogoutHook:

sudo defaults write LogoutHook /path/to/logoutscript

To delete we can run the following:

sudo defaults delete LoginHook
sudo defaults delete LogoutHook

As we can only list one script or file in the preferences, we can only have one LoginHook and LogoutHook systemwide.

It’s important that if we use a script, it must have the shebang at the header (e.g.: !#/bin/zsh).

Really that’s about it, it’s as simple as it looks.