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

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 »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.