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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.