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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.