TweetFollow Us on Twitter

MacEnterprise: Scripting Opportunities for System Administrators, Part One

Volume Number: 25
Issue Number: 06
Column Tag: MacEnterprise

MacEnterprise: Scripting Opportunities for System Administrators, Part One

When, where, why, and how you should run administrative scripts

By Greg Neagle, MacEnterprise.org

Introduction

In previous MacTech columns, I have sometimes offered up a script or two as part of a solution to a particular problem. Even if the script I presented is a perfect fit for your environment, you might still have had trouble making effective use of it in your organization, because you did not know how to make it run at the right time or in the correct context to get the job done.

This month, we'll begin a look at some of the many mechanisms available to run scripts (and other processes). Each mechanism has different uses and is suited for a unique set of tasks. Depending on what you need to accomplish, you should select the appropriate mechanism.

Why?

The first question you should ask is "Why do I want to run this script? What task do I want to accomplish?" Some of the common administrative categories that might lend themselves to scripting are:

System configuration - initial setup of the OS, networking, user accounts, etc.

System management - ongoing management of system settings; enforcing system-wide policies

User settings/preferences - configuring applications; setting up useful default preferences, enforcing user-level policies

Administrator tools - tools to make tedious or difficult tasks easier or more consistent

Hacks/fixes/workarounds - scripts to "fix" or work around problems with the OS or applications (or users!)

When?

Once you know why you are running the script, or what you want to accomplish with the script, you can consider when it should run. Some of the possibilities:

On demand - only when invoked by an admin or user

At startup

Repeating (daily/weekly/monthly, or other intervals like hourly, every 15 minutes, etc)

When a user logs in

When a user logs out

Let's look at some logical pairings of "Why?" and "When?":

Utility scripts or administrative tools that are to be run only on demand are the easiest to handle. Simply put them in a directory somewhere and run them manually as needed, or run them remotely using Apple Remote Desktop or SSH.

If your script is doing system configuration tasks like binding a machine to Active Directory or creating local users, it should almost certainly run at startup. System management tasks might run at startup, on a repeating schedule, or both.

Tasks that affect user settings or preferences should probably run at user login, or if it's a cleanup task, perhaps at user logout.

Hacks/fixes/workarounds can vary when it is appropriate to run them: they may need to run on demand; they may need to run at login to make a change to a user's environment; they may need to run at startup to clear out stale cached data.

How?

How can you run your script when you want? Let's look at some of the available mechanisms.

Running a script at startup

There are several ways to run scripts at startup, but the two most commonly used on Mac OS X are StartupItems and launchd items. Both Startup Items and launchd's LaunchDaemons run in the root context.

StartupItems

Startup items have been used on Mac OS X for a long time, and continue to work in OS X 10.5 Leopard. Administrator-provided Startup items should be placed in /Library/StartupItems. Since Apple is phasing out StartupItems, we won't spend a lot of time on these. A Startup Item consists of a directory containing an executable (typically a shell script) and a StartupParameters.plist file. Both the executable/shell script and the StartupParameters.plist have a very specific format. The startup item directory may optionally contain other items - for example, a Resources subdirectory. Apple has some good documentation on creating StartupItems here:

http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/StartupItems.html

launchd items

launchd was introduced with Mac OS X 10.4 Tiger. It was intended to replace almost every other way of launching processes, though in practice it has not yet accomplished that. Still, launchd is very capable, and Apple continues to enhance it. Launchd items are simpler to setup than StartupItems, as they generally require only a single additional file other than the actual script or executable. Administrator-provided launchd items that run a script at startup should go in /Library/LaunchDaemons.

Launchd has been covered extensively in MacTech as well as many other places, so I won't go into great depth. But let's do a quick example. Let's say we have a configuration script that we want to run at startup. It is located at /Library/Management/configuration.sh, and is marked as executable. It looks like this:

#!/bin/sh
logger -t configuration "Hello from the config script!"

This script simply writes a message to the system log. You can test it manually:

root# /Library/Management/configuration.sh
root# tail /var/log/system.log
<snip>
Apr 21 12:31:05 arcus configuration[8400]: Hello from the config script!

To get it to run at startup, you'd need a property list at /Library/LaunchDaemons/com.mactech.demo.plist that looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.mactech.demo</string>
   <key>ProgramArguments</key>
   <array>
      <string>/Library/Management/configuration.sh</string>
   </array>
   <key>RunAtLoad</key>
   <true/>
   <key>OnDemand</key>
   <true/>
</dict>
</plist>

This property list should have owner: root, group: wheel, and mode: 0644. Some explanation of the included keys:

Label is a string used by launchd to identify the job. The name of the plist file is usually the same as this label plus ".plist".

ProgramArguments is simply the full path to the executable script.

RunAtLoad is set to true so that launchd will run the job when it loads it, which is normally at startup.

OnDemand is set to true so that launchd won't attempt to restart the script once it exits - in other words, this process/script is not meant to run continuously.

We could test the launchd job by rebooting and then looking at the system log for our message, but rebooting can take a while, and if there's a problem, the fix/retest cycle is tedious. So let's do a quicker test:

root# launchctl load /Library/LaunchDaemons/com.mactech.demo.plist
root# tail /var/log/system.log
<snip>
Apr 21 12:31:05 arcus configuration[8400]: Hello from the config script!
Apr 21 12:37:13 arcus configuration[9073]: Hello from the config script!

At the end of the system log, you should see the message from the configuration script.

If you have problems, unload the job:

root# launchctl unload /Library/LaunchDaemons/com.mactech.demo.plist

Make your changes to the plist, and try loading the job again. Once the job is working, you should be able to reboot, and see the message in the system log during the startup process.

Apple documentation on creating a launchd item is available here:

http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/LaunchOnDemandDaemons.html

Repeating scripts

Some scripts are best run on repeating intervals. For example, you have a script that scans the startup disk for all installed fonts and then uploads that list of fonts to a database somewhere so you can monitor for license compliance. You should run that script periodically: maybe daily, maybe weekly, maybe monthlyÑit's up to your organization. There are several ways to do this.

One of the easiest ways is to piggy-back off an existing facility for running repeating scripts: the periodic command. By default, periodic is used to run scripts on a daily, weekly or monthly basis. It runs all the scripts it finds in certain directories:

/etc/periodic/daily/ - these are run every day

/etc/periodic/weekly/ - these are run once a week

/etc/periodic/monthly/ - these are run once a month

To get periodic to run your scripts, mark them as executable and put them in the appropriate directory. You can control the order in which the scripts run by naming them appropriately. The convention used is to start the script name with a three-digit number; the scripts are then run in numeric order:

root# ls -1 /etc/periodic/daily
100.clean-logs
110.clean-tmps
130.clean-msgs
430.status-rwho
500.daily
599.randomSleep
600.updateMachineName
700.updateHostInfo
900.autoradmind

There are some issues to be aware of, however. The first is exactly when these scripts will run. This is controlled by launchd in the following files in /System/Library/LaunchDaemons:

com.apple.periodic-daily.plist
com.apple.periodic-monthly.plist
com.apple.periodic-weekly.plist

Looking at com.apple.periodic-daily.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.apple.periodic-daily</string>
   <key>ProgramArguments</key>
   <array>
      <string>/usr/sbin/periodic</string>
      <string>daily</string>
   </array>
   <key>LowPriorityIO</key>
   <true/>
   <key>Nice</key>
   <integer>1</integer>
   <key>StartCalendarInterval</key>
   <dict>
      <key>Hour</key>
      <integer>3</integer>
      <key>Minute</key>
      <integer>15</integer>
   </dict>
</dict>
</plist>

The StartCalendarInterval key tells us it will run each day at 3:15 AM local time. That time might not be a good one for your environment. Consider a few scenarios:

Desktop machines: if the desktops in your organization are left on 24/7, then the script will run shortly after 3:15 AM each day. If instead, they are asleep at 3:15 AM, they'll run shortly after they are woken up each day. If they are powered off at 3:15 AM, the scripts won't run at all. Launchd will reschedule jobs that were scheduled to run when the machine was asleep, but will not reschedule jobs that were scheduled to run when the machine was powered off.

Laptop machines: all of the same complications as with desktops, with the additional problem that if they get taken home at night or over the weekend, and run these jobs at 3:15 AM (or when woken up), and your scripts require access to network services or resources available only when the machine is connected to your organization's network, they may fail, or at the very least, fail to do anything useful.

Therefore, you might consider changing the time these jobs run to a time during the day when it's more likely the machine is on, awake, and on your network.

Another possible approach that does not require modifying Apple's provided launchd items is to run a script at startup that checks for overdue periodic jobs and runs them. Such a script is described (and available) here:

http://managingosx.wordpress.com/2008/06/18/launchd-vs-periodic/

Repeating launchd jobs

Looking at the property list for com.apple.periodic-daily.plist suggests another method for running scripts on a repeating basis: avoiding the periodic middleman and using launchd directly. Using our com.mactech.demo example as before, we can run a script at startup and once a day with a LaunchDaemon plist like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.mactech.demo</string>
   <key>ProgramArguments</key>
   <array>
      <string>/Library/Management/configuration.sh</string>
   </array>
   <key>RunAtLoad</key>
   <true/>
   <key>OnDemand</key>
   <true/>
   <key>StartCalendarInterval</key>
   <dict>
      <key>Hour</key>
      <integer>12</integer>
      <key>Minute</key>
      <integer>15</integer>
   </dict>
</dict>
</plist>

We've added a StartCalendarInterval to the previous version of the property list that tells launchd to run the job each day at 12:15, when many of our staff will be at lunch. If we didn't want it to run at startup as well, we could remove the RunAtLoad key, or set it to false.

Good old cron

One last method to mention: the classic UNIX cron is still available in OS X, and can still be used to run repeating jobs. Type man cron at a command prompt for details. You'll probably want to create a crontab at /etc/crontab . A big disadvantage of using cron is that it's hard to manage different versions of the crontab files. For example, if you have a set of machines that need repeating jobs A and B, another set that needs repeating jobs B and C, and yet another set that needs repeating jobs A, B and C, you'll need to manage three different versions of the crontab as well as the scripts that do the actual jobs. If you use periodic or launchd, you don't have to deal with the monolithic crontab file, as the scheduling info for each job lives in a separate file (or in the case of periodic, is not needed).

To be continued...

We covered quite a bit this month. We looked at running scripts at startup and on a repeating schedule. In the future, we'll look at running scripts as part of the login and logout process, both with root privileges, and as the user logging-in. While you might guess that launchd might be useful here, we'll also look at login/logout hooks and login items. We'll also consider the special case of 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. See you next time!


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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.