MacEnterprise: Scripting opportunities for
System Administrators, part 2
Volume Number: 25
Issue Number: 07
Column Tag: MacEnterprise
MacEnterprise: Scripting opportunities for
System Administrators, part 2
Running administrative scripts at login
and logout, and more
By Greg Neagle, MacEnterprise.org
Introduction
In an earlier issue of MacTech, we started a look at scripting opportunities for systems administrators. We talked about why you might want to run a script, when it's possible and advisable to run scripts for certain tasks, and began to look at exactly how you get your scripts to run at the right time.
Previously, we discussed running scripts at startup and on a repeating schedule. This month, we'll look at running scripts as part of the login and logout process, both with root privileges, and as the user logging in. We'll also consider scripts that should run only once, either at startup or login. Finally, we'll look at some methods to simplify implementing additional scripts once you have a few working.
Login/Logout hooks
A very common administrative need is to run a script (or scripts) when a user logs in or when a user logs out. One possible reason to do this is that you need to make a change to the user's environment: maybe you need to redirect a network user's caches to the local disk before they complete their login, or you need to do some cleanup on logout.
If you need to run a script at each user login, and the script must have superuser (root) privileges, you should consider implementing a login hook. A login hook is a script that runs as part of the login process. It runs after the user's home directory has been mounted (if it's a network user or one whose home directory has been protected with FileVault). It runs as root, but is passed the name of the user who is logging in.
To set up a login hook, make sure your script is executable:
sudo chmod 755 /path/to/script
Then set the loginhook:
sudo defaults write com.apple.loginwindow LoginHook /path/to/script
Log out and back in, and the hook should run. Logout hooks are set up similarly:
sudo defaults write com.apple.loginwindow LogoutHook /path/to/script
Here's an example of a script that could be used as a logout hook. On logout, it randomly selects a picture to use as the desktop picture/background behind the loginwindow.
#!/usr/bin/perl -w
use strict;
my $loginwindowprefs = "/Library/Preferences/com.apple.loginwindow";
my $picdir = "/Library/Desktop Pictures/Nature";
if ( -d "$picdir") {
my @list = split("\n",`ls -1 "$picdir"`);
my @pictures = ();
for my $item (@list) {
if (-f "$picdir/$item") {
push @pictures, "$picdir/$item";
}
}
if (scalar(@pictures)) {
my $currentpicture = `/usr/bin/defaults read $loginwindowprefs DesktopPicture`;
if ($currentpicture) { chomp($currentpicture) };
my $randompicture = $currentpicture;
while ($randompicture eq $currentpicture) {
my $randomindex = int(rand(scalar(@pictures)));
$randompicture = $pictures[$randomindex];
}
my $result = `/usr/bin/defaults write $loginwindowprefs DesktopPicture "$randompicture"`;
}
}
Figure 1. MCX login scripts
Each time a user logs out, the picture behind the loginwindow is changed. Since this script runs during logout, but before the loginwindow is displayed, you should see a new picture at each logout.
Apple's Knowledge Base article on setting up a login hook is here: http://support.apple.com/kb/HT2420
MCX login scripts
There is another way to specify a specific script to run at login or logout, and that is using MCX via Workgroup Manager (Figue 1, above).
Using MCX to manage login scripts requires very specific client settings and can be tricky to get right. Make sure to read the relevant help information, accessible by clicking the purple question mark in Workgroup Manager.
Other login options
Login hooks run as the root user. There are tasks that require running as the user logging in. For these, you have a few options:
Use a login hook, but within the hook, act as the user with the su command. This can be tricky to get right.
Implement it as a launchd LaunchAgent.
Write your script as a launchable application and add it to the login items.
LaunchAgents
LaunchAgents had some pretty serious shortcomings in Tiger, but in Leopard, they are pretty useful.
A LaunchAgent is started when a user logs in, and runs as that user. As the system administrator, you should put LaunchAgent plists in /Library/LaunchAgents. /System/Library/LaunchAgents is reserved for use by Apple, and ~/Library/LaunchAgents is for the user's personal use.
Let's say you wanted to run a script at user login that would launch a setup assistant-type application - a LaunchAgent would be a good fit for this. Here's an example plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>org.mactech.demolaunchagent</string>
<key>LimitLoadToSessionType</key>
<string>Aqua</string>
<key>Program</key>
<string>/Library/Management/runSetupAssistant.pl</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
This LaunchAgent plist has a unique label, which is simply a name for the task. A new key introduced in 10.5 Leopard is LimitLoadToSessionType, and here it is set to Aqua. This tells launchd to load the job only when there is a GUI login - if the user were to login via SSH, for example, the job would not run. This makes sense for this, as we wouldn't want our GUI setup assistant application to run if the user wasn't logging into the GUI console. If you had a job that made sense to run only for a non-GUI login, you would set the value of LimitLoadToSessionType to StandardIO. Finally, the RunAtLoad key is set to true to tell launchd to run the script immediately when loading the job after login.
For more information about LaunchAgents and their options, see this Apple Technical Note: http://developer.apple.com/technotes/tn2005/tn2083.html
Last time I promised that I'd cover scripts that should run only once. A classic case is a script that launches a setup assistant. You might want it to launch the assistant the first time a user logs in, but you probably don't want it to launch every time the user logs in. Here's how you might handle this:
#!/usr/bin/perl
#run the Setup Assistant if it's never run before
$homedir = $ENV{'HOME'};
$checkFile = "$homedir/.my.org.setupassistant";
unless (-f "$checkFile") {
`touch $checkFile`;
`open "/Applications/Utilities/My Org Setup Assistant.app"`;
}
Here's what's happening. We define a filename - ".my.org.setupassistant". We start the name with a period so it is invisible in the Finder. The script checks for the existence of the file in the root of the current user's home directory. If it's not present, the script creates the file and opens the Setup Assistant. The next time the script runs for this user, the file will exist, and the script will exit without opening the Setup Assistant.
You can use this same basic technique for any script you want to run just once - the script actually runs at each startup/login/etc, but exits without doing anything if a certain file exists. In my opinion, this is a better approach than a script that removes itself after it runs because you can easily re-run the script in the future simply by removing its "flag" file.
Login items
There is another type of item that runs at user login. It's usually referred to as a login item, though an earlier version of Mac OS X confusingly called these "startup items". Users can add their own login items, either from the Accounts pane of the System Preferences application, or by right-clicking or control-clicking on an item in the Dock and choosing Open at Login from the contextual menu that appears.
Figure 2. Setting an item to open at login
What a system administrator needs, though, is a way to specify that certain items open for all users of a given machine. There are two ways to do this. The first, if you are using MCX, is to add the items to the managed login preferences using Workgroup Manager. The second is to add the items to the file at /Library/Preferences/loginwindow.plist:
> defaults read /Library/Preferences/loginwindow AutoLaunchedApplicationDictionary
(
{
Hide = 1;
Path = "/Library/Management/LoginLauncher.app";
}
)
Applications added here are launched for all users of a given machine at login, in addition to whatever items a user may have added to their own list of login items. Note that the name of the key is AutoLaunchedApplicationDictionary - you have to add applications here, and not scripts - even if they are set as executable. In order to use this mechanism to run scripts, you need to either wrap your script into an application bundle, or write an app whose purpose is to run your scripts. Fortunately, I've done that work for you. A link to such an application can be found in the next section of this article.
Running multiple scripts
A major problem with login/logout hooks is that there is support for only a single login/logout script. This can be a problem if you need to implement more than one script. A solution to this problem is to implement master login/logout hooks, which in turn run additional scripts within a given directory. Here's a sample master login hook:
#!/bin/sh
# Master login hook script
# runs each script found in the login hooks directory
LOGINHOOKSDIR="/etc/hooks/login"
if [ -d ${LOGINHOOKSDIR} ]; then
for script in ${LOGINHOOKSDIR}/* ; do
if [ -s ${script} -a -x ${script} ]; then
# log this run
logger -s -t LoginHook -p user.info Executing ${script}... 1>&2
# run the item.
${script} $*
# if there was an error, log it
rc=$?
if [ $rc -ne 0 ]; then
logger -s -t LoginHook -p user.info ${script} failed with return code ${rc} 1>&2
exit $rc
fi
fi
done
fi
exit 0
This master hook loops through all the items in the /etc/hooks/login directory, checks to see if each item is non-zero-length and executable, and if so, writes a message to the system log announcing it's running the item, and then runs the item, passing along any command-line parameters that were sent to the master hook. A similar script could be used to run multiple logout hooks.
In fact, this technique is useful in other scripting situations. If you create a launchd plist to run a specific script at startup, and later you want to run another script as well, you'd have to create another launchd plist for the second script. This quickly gets tedious and error-prone. If, instead, you created a script like the master loginhook that ran all the scripts in a certain directory, and created a launchd plist to run that script, then to run additional scripts, you'd only have to put them in the special directory. This enables you to do the hard work once and then add or subtract scripts as needed.
Another variation of this technique can be used to run scripts at login as the user who is logging in. You can get details on doing this at the MacEnterprise.org site:
http://www.macenterprise.org/articles/runningitemsatlogin
Conclusion, and More info
That concludes our look at scripting opportunities. You should now have a better idea how you can get your scripts to run at the proper time and in the proper context. Below, I've listed a few more places to get more info on some of the topics we've discussed. Good luck!
More options for running code at login, and a discussion of the pros and cons of each:
http://developer.apple.com/technotes/tn2008/tn2228.html
launchd, LaunchDaemons, and LaunchAgents:
http://developer.apple.com/technotes/tn2005/tn2083.html
http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/LaunchOnDemandDaemons.html
Login items, login/logout hooks, and LaunchAgents:
http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html