TweetFollow Us on Twitter

MacEnterprise: System Framework Scripting

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

MacEnterprise: System Framework Scripting

Using system frameworks in scripts for systems administration

By Greg Neagle, MacEnterprise.org

Introduction

A very important tool in the systems administrator's tool kit is scripting. It's often been said that a good systems administrator is a lazy systems administrator. A good sysadmin will try to minimize the number of repetitive tasks he or she has to perform by automating them. What good are all our fancy computers if we cannot get them to do our boring work for us? So it is very common for a systems administrator to use scripting to automate a repetitive, complex and/or error-prone task.

Several common systems administration problems can often be solved through the use of creative scripting. You could have a script that runs system_profiler on all your Macs and uploads information about all your machines to a central database. Scripts can help with the initial setup of a machine, or initial application configuration. Scripts can monitor for problems and report them to you.

Another typical use for scripting is to fill in missing functionality. An example: Apple's Energy Saver can sleep an idle machine, or shut down and wake up a machine on a schedule. But what if you wanted Energy Saver to leave a machine alone between 8:00 am and 6:00 pm, but outside of those hours, you'd like it to sleep idle machines or even shut them down. Energy Saver's preferences don't offer this functionality, but you can easily script this using either the pmset or systemsetup command-line tools.

Scripting Languages

There are many scripting languages available in a default install of OS X 10.5. Among them are AppleScript, the traditional shell languages – sh, csh, tsch, zsh and bash; Perl, PHP, Python, and Ruby. So which do you use? The answer, of course, is "it depends."

The shell languages are among the easiest to get started in for simple tasks, as you can often just list the commands you want to perform, just as if you'd typed them at the command line. Here's an example of a simple shell script that configures time and date settings:

#!/bin/sh
/usr/bin/systemsetup –setnetworktimeserver time.myorg.org
/usr/bin/systemsetup –setusingnetworktimeon
/usr/bin/systemsetup –settimezone "America/Los_Angeles"

This script only calls one tool – systemsetup – to do its work, but it is common to call several command-line tools in scripts to complete a given task. Let's say we want to configure Energy Saver settings, but only on desktop machines – we'll leave laptops alone. So we need a way to tell if the script is running on a laptop, and we need a way to set Energy Saver settings. system_profiler can tell us the machine model, and pmset can set Energy Saver settings, so it makes sense to use those tools for a script:

#!/bin/sh # check to see if we're a laptop IS_LAPTOP=`/usr/sbin/system_profiler SPHardwareDataType | grep "Model" | grep "Book"` if [ "$IS_LAPTOP" = "" ]; then # sleep never, disk sleep in 10 minutes, # display sleep in 30 minutes pmset -c sleep 0 disksleep 10 womp 1 displaysleep 30 fi

In this example, we call use grep to filter the output from system_profiler, looking for "Book" in the Model Name. Here's how those steps look from the command line:

> system_profiler SPHardwareDataType | grep "Model" | grep "Book"
      Model Name: MacBook Pro
      Model Identifier: MacBookPro5,1

This works because all Apple laptops to date have "Book" in their names (PowerBook, iBook, MacBook, MacBook Pro, MacBook Air). If we find "Book", then the machine we're running on is a laptop. If we don't find "Book", we use the pmset command to set the power management options we want for desktop machines. This shell script uses three command-line tools (system_profiler, grep, and pmset) to do its thing.

You can certainly do more complex things in shell languages, but it's difficult to work with complex data structures like arrays and dictionaries, and there's no support for object-oriented programming. For simple tasks like the above, it may not be worth the effort of writing the script in anything other than shell. But once your script reaches a certain level of complexity, you should consider using a higher-level scripting language like Perl, Python, or Ruby.

Higher-level scripting languages

Two higher-level languages commonly used for systems administration tasks are Perl and Python. Perl has a large number of available libraries, and does text manipulation really well. This shouldn't be surprising, since Perl was originally written to make report processing easier.

In recent years, Python has been gaining popularity as a systems administration language. There are some key features that make Python attractive for this task. First, a core design goal for Python is to maximize its readability. Python programs tend to be easier to read, and therefore easier for others to understand and maintain. This is no small feature in an organization where a systems administrator may be called to fix or extend a script written by someone else. Another feature adding to Python's suitability for systems administration tasks is its large and useful standard library.

With the 10.5 release of OS X, there is another reason to consider Python for systems administration tasks: easy access to system frameworks.

Why Frameworks?

As a systems administrator, if you need to script a task, typically one of the first things you do is look for command-line tools to do some or most of the work. In the earlier shell scripting examples, we used the command-line tools systemsetup, system_profiler, grep, and pmset. There are many, many other command-line tools of use to a systems administration scripter.

But what if the functionality you need is not available in a command-line tool? There are many things you can do in OS X that are not available via the command-line. If you are scripting in shell and need access to functionality not exposed via a command-line tool, you might be out of luck. But if you are using Python or Ruby, Apple has included "bridges" to some of the system frameworks, allowing you to call native OS X methods from inside your Python or Ruby script.

Framework Example

Let's look at an example where access to a system framework can help solve a systems administration problem.

OS X systems administrators are familiar with OS X's standard method of storing and retrieving preferences. Sometimes referred to as the "defaults" system, preferences are stored in plist files located in /Library/Preferences, ~/Library/Preferences, and ~/Library/Preferences/ByHost. Additionally, some preferences can be managed via MCX. A problem is determining the "effective" preferences – that is, what preferences are actually in effect for the current user on the current machine.

Apple provides some command-line tools: defaults can read the user's on-disk preferences and return them, but it isn't MCX aware, so managed preferences are not found by the defaults tool. The mcxquery tool can list all of the managed preferences in effect for a given user and/or computer, but it's up to you to parse that information to find the preference domain and key you are interested in. There is no command-line tool that allows you to ask for the value of a specific preference that returns the effective value taking into consideration MCX settings.

Since Python can access OS X system frameworks, and since the information we need can be obtained by calling some functions in the CoreFoundation framework (namely the CFPreferences functions), we can write a tool in Python to give us the information we want. Here's the basic idea:

#!/usr/bin/env python
import sys
import CoreFoundation
preferenceDomain = sys.argv[1]
keyName = sys.argv[2]
print CoreFoundation.CFPreferencesCopyAppValue(keyName, preferenceDomain)
if CoreFoundation.CFPreferencesAppValueIsForced(keyName, preferenceDomain):
    print "*** %s is managed always by MCX ***" % keyName
The main bit of magic is the line:
import CoreFoundation

which imports the CoreFoundation framework, where the CFPreferences functions are defined. Once we import this framework, we can call the CFPreferences functions just as if they were defined in a Python library.

CoreFoundation.CFPreferencesCopyAppValue(keyName, preferenceDomain) gives us the value defined for the key keyName in the preferences domain preferenceDomain, no matter where this is defined – in ByHost preferences, user preferences, system-wide preferences, or managed preferences (those managed by MCX).

CoreFoundation.CFPreferencesAppValueIsForced(keyName, preferenceDomain) can tell us if this value is being "forced" by MCX – that is, the value is set to be managed "always".

Let's look at it in action. I've named this script "effective_defaults". First, let's read a preferences setting using the built-in defaults command:

> defaults -currentHost read com.apple.screensaver askForPassword
2009-06-27 18:28:09.312 defaults[58288:807] 
The domain/default pair of (com.apple.screensaver, askForPassword) does not exist
The defaults command would lead us to believe that the screensaver will not ask us for a password, yet on my laptop, it does. Let's see what our effective_defaults script says:
> ./effective_defaults com.apple.screensaver askForPassword
1
*** askForPassword is managed always by MCX ***

Since this script uses CFPreferences, it is MCX-aware, and returns "1" for the setting, and tells us MCX is managing this value "always".

Another example – on my machine, the loginwindow displays username and password fields, not a list of users. Why is that? Let's ask defaults:

> defaults read /Library/Preferences/com.apple.loginwindow SHOWFULLNAME
2009-06-27 18:53:49.470 defaults[58353:807] 
The domain/default pair of com.apple.loginwindow, SHOWFULLNAME) does not exist

This tells us that the SHOWFULLNAME preference is not set in /Library/Preferences/com.apple.loginwindow.plist. Now, let's ask using the Python script:

> ./effective_defaults com.apple.loginwindow SHOWFULLNAME
True
*** SHOWFULLNAME is managed always by MCX ***

Again, it finds the MCX-managed value and reports it. Let's check to make sure it does the right thing when the value is not managed by MCX. I've set the image that appears behind the loginwindow to a custom image. Let's check it both ways:

> defaults read /Library/Preferences/com.apple.loginwindow DesktopPicture
/Library/Desktop Pictures/Disney/Goofy.jpg
> ./effective_defaults com.apple.loginwindow DesktopPicture
/Library/Desktop Pictures/Disney/Goofy.jpg

We see that both methods return the same value. Notice that in the effective_defaults script, we don't have to know that the value is stored in the file in /Library/Preferences, and in fact we cannot specify a file path, only a preferences domain.

Improving the script

Let's return to the script for a bit. It's actually not very well written – if we pass the wrong number of parameters, it fails unhelpfully:

> ./effective_defaults com.apple.loginwindow
Traceback (most recent call last):
  File "./effective_defaults", line 7, in <module>
    keyName = sys.argv[2]
IndexError: list index out of range

This is because we didn't do any kind of error checking or error-handling. Let's fix that:

#!/usr/bin/env python
import sys
import CoreFoundation
try:
    preferenceDomain = sys.argv[1]
    keyName = sys.argv[2]
except:
    print "Usage: %s <domain> <key>" % sys.argv[0]
    print "\tWhere <domain> is a valid preferences (defaults) domain,"
    print "\tand where <key> is a valid preferences key"
    print
    print"Example: %s com.apple.screensaver askForPassword" % sys.argv[0]
    exit(-1)
    
print CoreFoundation.CFPreferencesCopyAppValue(keyName, preferenceDomain)
if CoreFoundation.CFPreferencesAppValueIsForced(keyName, preferenceDomain):
    print "*** %s is managed always by MCX ***" % keyName

All we've done here is wrap the code that gets the parameters with a try/except block. If there's a problem, we print a usage statement and exit. Now let's try it:

> ./effective_defaults com.apple.loginwindow 
Usage: ./effective_defaults <domain> <key>
   Where <domain> is a valid preferences (defaults) domain,
   and where <key> is a valid preferences key
Example: ./effective_defaults com.apple.screensaver askForPassword

There's certainly more that could be done to improve and extend the script, but this gets the basic functionality running and handles the most common error cases.

More Frameworks

Being able to access system frameworks opens up an entirely new realm of tools for systems administrators to use to solve problems. In many ways, systems administrators using Python or Ruby have almost as many options as people coding in lower-level languages like Objective-C, C, or C++. A better developed, and more generally useful example is crankd. crankd is a Python project that began as a replacement for the Kicker.bundle functionality in older versions of OS X. Prior to Leopard, systems administrators could use the SystemConfiguration Kicker.bundle to run scripts when the network configuration changed – the computer connected or disconnected from a network, or the IP address changed, or similar network events. But with the release of OS X 10.5 Leopard, the Kicker.bundle disappeared, and there was no obvious replacement method for systems administrators to run scripts based on network changes. (To be fair, Apple never officially supported the use of the Kicker.bundle in this manner).

Chris Adams and Nigel Kirsten collaborated on what became crankd, which is part of PyMacAdmin, a collection of Python-based utilities of interest to Mac systems administrators. PyMacAdmin uses Python and its ability to call system code to do things that are impossible or difficult from command-line tools.

crankd not only replaces the lost Kicker functionality, but adds much more. With crankd, you can watch for network changes, filesystem activity, application launches, volume mounting/unmounting, system sleep/wake, and more. When any of these events occur, crankd can run a script or call a Python method.

crankd makes use of the Cocoa, SystemConfiguration and FSEvents frameworks. Other PyMacAdmin tools make use of the Security and CoreFoundation frameworks, so if you are looking for more examples of how to work with OS X system frameworks with Python from a systems administration perspective, this is a good place to start.

Check out crankd and the other PyMacAdmin tools at http://code.google.com/p/pymacadm.

Where to Go from Here

You've now seen how you can work with OS frameworks in Python scripts. When scripting, you now have a whole new set of resources you can use to accomplish your task. To find out more about the various frameworks so you can use them in your Python scripts, start with Apple's documentation, both online and included with the Xcode tools.

Calling system frameworks in scripts is not limited to Python. Apple ships the RubyCocoa bridge with Leopard, which enables Ruby scripts to call Objective-C frameworks. And finally, there is CamelBones, a third-party bridge between Perl and Objective-C.

Apple documentation on Python and Ruby on Mac OS X, including info on the Cocoa bridges:

http://developer.apple.com/documentation/Cocoa/Conceptual/RubyPythonCocoa/Articles/RubyPythonMacOSX.html

Apple Cocoa documentation:

http://developer.apple.com/documentation/Cocoa/index.html

Apple documentation on CFPreferences:

http://developer.apple.com/documentation/CoreFoundation/Conceptual/CFPreferences/CFPreferences.html

Official PyObjC site:

http://pyobjc.sourceforge.net/

RubyCocoa site:

http://rubycocoa.sourceforge.net/HomePage

CamelBones, the Perl/Objective-C bridge:

http://camelbones.sourceforge.net/index.html

And in a recent MacTech:

Mac in the Shell: Python on the Mac: PyObjC, Edward Marczak, June 2009

If you have Xcode installed, (and as a MacTech-reader, you should) you'll find PyObjC examples at /Developer/Examples/Python/PyObjC and RubyCocoa examples at /Developer/Examples/Ruby/RubyCocoa.


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

The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
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 »

Price Scanner via MacPrices.net

Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.