TweetFollow Us on Twitter

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


Greg Neagle is a member of the steering committee of the Mac OS X Enterprise Project (macenterprise.org) and is a senior systems engineer at a large animation studio. Greg has been working with the Mac since 1984, and with OS X since its release. He can be reached at gregneagle@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.