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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but 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 MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
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
Amazon has clearance 9th-generation WiFi iPad...
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
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance 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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
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.