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

Chromium 119.0.6044.0 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. List of changes available here. Version for Apple... Read more
Spotify 1.2.21.1104 - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more

Latest Forum Discussions

See All

‘Monster Hunter Now’ October Events Incl...
Niantic and Capcom have just announced this month’s plans for the real world hunting action RPG Monster Hunter Now (Free) for iOS and Android. If you’ve not played it yet, read my launch week review of it here. | Read more »
Listener Emails and the iPhone 15! – The...
In this week’s episode of The TouchArcade Show we finally get to a backlog of emails that have been hanging out in our inbox for, oh, about a month or so. We love getting emails as they always lead to interesting discussion about a variety of topics... | Read more »
TouchArcade Game of the Week: ‘Cypher 00...
This doesn’t happen too often, but occasionally there will be an Apple Arcade game that I adore so much I just have to pick it as the Game of the Week. Well, here we are, and Cypher 007 is one of those games. The big key point here is that Cypher... | Read more »
SwitchArcade Round-Up: ‘EA Sports FC 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2023. In today’s article, we’ve got a ton of news to go over. Just a lot going on today, I suppose. After that, there are quite a few new releases to look at... | Read more »
‘Storyteller’ Mobile Review – Perfect fo...
I first played Daniel Benmergui’s Storyteller (Free) through its Nintendo Switch and Steam releases. Read my original review of it here. Since then, a lot of friends who played the game enjoyed it, but thought it was overpriced given the short... | Read more »
An Interview with the Legendary Yu Suzuk...
One of the cool things about my job is that every once in a while, I get to talk to the people behind the games. It’s always a pleasure. Well, today we have a really special one for you, dear friends. Mr. Yu Suzuki of Ys Net, the force behind such... | Read more »
New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »

Price Scanner via MacPrices.net

Clearance M1 Max Mac Studio available today a...
Apple has clearance M1 Max Mac Studios available in their Certified Refurbished store for $270 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Apple continues to offer 24-inch iMacs for up...
Apple has a full range of 24-inch M1 iMacs available today in their Certified Refurbished store. Models are available starting at only $1099 and range up to $260 off original MSRP. Each iMac is in... Read more
Final weekend for Apple’s 2023 Back to School...
This is the final weekend for Apple’s Back to School Promotion 2023. It remains active until Monday, October 2nd. Education customers receive a free $150 Apple Gift Card with the purchase of a new... Read more
Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* River -...
Park Dental Apple River in Somerset, WI is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. COMPETITIVE PAY AND SIGN-ON Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Sep 30, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* / Mac Administrator - JAMF - Amentum...
Amentum is seeking an ** Apple / Mac Administrator - JAMF** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter 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.