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

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
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 below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.