Developer

AppleScript and your network

AppleScript is a system-level, English-like scripting language that can bind the Mac OS and applications together. In this article, Ilene Hoffman demonstrates how AppleScript can help you administer a network.


One of the biggest headaches in network administration is repetition. From running backups, to building new machines, to fixing yet another jammed printer, much of a network administrator's day is like the previous day—and will be the same tomorrow. In the Mac world, this doesn't change. Repetition is still repetition, though it may be prettier.

So how do we automate some of these repetitious tasks and get them done on time but without someone actually doing them? For the Mac administrator, the answer is AppleScript. AppleScript is a system-level, English-like scripting language that can bind the Mac OS and applications together to perform operations you now do manually. AppleScript works by sending messages through a messaging tool called AppleEvents. The messages are sent between the Mac OS and supported applications.

AppleScript is bundled with the Mac OS and comes with sample scripts and background information. You can use this powerful tool for everything from final assembly of newspapers, to multimedia scripting, to network administration. In short, if you want to automate a job, there's an excellent chance that AppleScript can help. In this article, I’ll show how AppleScript can help you administer a network.

Know your network and access your tasks
First, to script a network, you have to know your network, not just the type of network, such as Ethernet. You need the nitty-gritty details, including the physical location of wires and of each piece of equipment that may be affected by your scripting. In addition, you need details, such as the difference between the physical and logical layout of your network, how the network was built, and why it was built that way. You also need to know exactly what computers and operating systems are on the network that you want to automate. Just as important is what the users are really using on those computers, not what you think they’re doing with them.

The reason for collecting this type of information is simple: When you script a network, you control it. To really control something, you need intimate knowledge of what it is and how it behaves. This knowledge helps you to avoid problems later on down the road.

The next factor to look at is the tasks you perform multiple times that you want to automate. License monitoring, application and OS updates or installs, statistics collection, and usage monitoring are tasks that lend themselves to automation. You must also look at how often these tasks need to be performed. How long does each task take, and which tasks have priority? Analyzing these details avoids problems later.

Plan the automation process
The planning of automation is often skimmed over, but it is critical. A lot of folks jump headfirst into scripting and start a huge project that fails or is never completed. Find out which tasks need your control and which processes are running just fine without intervention. The question to ask yourself is, "Is this an appropriate task for scripting?" If scripting a task means you never have to think about doing that task again, then full speed ahead! If automation is going to save you only three mouse clicks a month, it probably isn't worth the effort.

Also, how mindless is the task? If you know you could train a chimpanzee to do it, then script away. But if it's a delicate task that requires a lot of mothering, think hard on the appropriateness of scripting it. Finally, what do you want out of the script; what is the end result? Some results are easy to accomplish via scripting; others may not be worth the effort.

Applications and scripting
The first rule of scripting is don't reinvent the wheel! Before you start writing the Great American AppleScript, make sure you don't duplicate work that someone else has already done. Even a small script can take five to eight hours to perfect. If someone else has written an application that can do what you need, and it costs less than five hours of your time, buy the application. This saves a lot of time and aggravation.

You cannot script everything. Many scriptable network administration applications are available, so take advantage of them. Gluing two or three applications together is always easier than doing 100 percent of the work in the script. For example, if you need e-mail notification, use a scriptable e-mail program. Take a look at these applications as well as others to determine whether they can make your life easier by giving you a better set of scripting tools.

Examples of excellent scriptable applications
BBEdit, a text editor from Bare Bones Software Retrospect, backup software from Dantz Development

Scripting fundamentals
There are certain fundamental principles that John Welch, a network administrator for AER Inc., a weather and atmospheric science company in Cambridge, MA, tries to follow when scripting a network task. He suggests you ask yourself the following:
  • ·        What: What are you trying to accomplish? Do you have the specific task clearly defined, in both scope and purpose? For the network administrator, many small, single-purpose scripts are better than a monstrous hydra of a script. A general rule of thumb with regard to size is if it's too big for Apple's Script Editor, it's probably too big to be effective. Keep the size of your scripts manageable. Remember, most administering scripts don't have a real user interface; the scripts should be able to run unattended for months. This means that reliability is the most important quality for these scripts. Since smaller scripts are inherently easier to maintain, scripts should be simple and small. This is not to say function should be sacrificed in the name of brevity but that bloat should be avoided at all costs.
  • ·        Where: Most of the admin scripts John uses are server-based, so the location of the script server becomes important. While the size of the server is dependent on the scripts, it’s not unusual to discover that the more you script, the more you script. In other words, use at least a Macintosh Beige G3, with no less than 128 MB of RAM. Before you recoil in horror, remember that Mac OS 9.0, which you need to script over TCP/IP, uses between 30 and 50 MB for this type of work. Consequently, 128 MB leaves you with about 70-90 MB of RAM for the scripts and their applications. Another factor to consider is existing load. If the box in question is already being used as a server for CPU- or I/O-intensive activities, you may want to use another computer. Two applications that come to mind are Retrospect and FileMaker Pro. Both of these applications place large demands on all available CPU time and I/O bandwidth and should not be used on script servers. If you run a Mac with AppleShare IP (ASIP) 6.2 and higher, you can use it as a script server, provided that it’s not already running at full capacity. Ideally, a dedicated Mac is the best choice. Other than RAM and hard drive space, the only other requirement is a current OS. Use at least Mac OS 9.x if you want to be able to run remote scripts over TCP/IP. A script scheduler, such as the iDO Script Scheduler, is also needed for timed or repeating scripts.
  • ·        When: In general, try to avoid scripts that have to run at a specific time and cannot be run any other time. Instead, use scripts that can be run during low usage hours, within a given range of times and days. This will give you the flexibility to work around the load peaks on your network. For example, scheduling a full install of Microsoft Office 98 on 30 Macs at the same time your backups are running is not the best idea. John recommends running scripts during the early morning hours, between 1 and 5 A.M., when the machines are usually idle. This range of time also allows you to balance CPU and I/O resources to their optimal levels. Above all, avoid seeing how slick you can be with time scheduling—leaving little margin for error is just begging for repeated visits from Murphy's Law.
  • ·        Why: Why are you scripting this task? Is there a definite need for it, or are you scripting something because you can? Sometimes, performing the task manually is the better way to do it. Do a needs assessment to determine the task, the time to build the script, the need for automation, and the time saved if the task is scripted. Remember, the whole idea behind scripting is to make your life easier. If you replace a monthly, five-minute job with a balky script that takes 20 minutes to run—and a week to write the silly thing—you have improved nothing.
  • ·        How: Plan your script, and script your plan. Know exactly what you want to do before you sit down to create a script. Once you have your plan, don't deviate from it. For most scripting tasks, Script Editor is a good choice. This simple tool forces you to think simply. Occam's Razor—that a problem should be stated in its basic and simplest terms—is a good guide here. Also, build your script in stages. Each script has a core function, so build this first. Once this function works, add only those features that are needed. Remember, this script has to work, even when you aren't. Don't be afraid to ask for help. The AppleScript list is an excellent resource. Some of the true luminaries of the scripting world are active participants, and you can often get help within an hour of posting a message. One trick is to build a library of core functions that can be pasted into new scripts. This prevents you from having to reinvent the wheel. Again, simplicity is the mantra of the network scripter.

Some sample scripts
Here are some scripts used by AER Inc. network administrator John Welch. (For more information about John, click on Scripting Fundamentals which appears on the right hand navigation bar.) The first is one of the scripts he runs for his Windows NT 4 computers after the OS is installed and configured. Since he uses ASIP's Windows networking features, he needs NT to be able to send plain-text passwords to the ASIP servers; Service Pack 3 for NT doesn't do this without a simple registry modification. John uses netOctopus and AppleScript, and he can do this remotely, without the specter of a typo killing his NT box.
property NoSelectionErr : "There is no computer selected. Please select one!"

tell application "netOctopus"
set theWindow to window "Computers"

set theSelection to selection of theWindow
if theSelection exists then
add registry value of theSelection registry key path "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\
Services\\Rdr\\Parameters" registry value name "EnablePlainTextPassword" registry value type number value registry value "1"
else
display dialog NoSelectionErr buttons {"Okay"} with icon stop
end if
end tell


The first line sets up the error message if the script is run without selecting a computer first. The second line is where netOctopus is being set as the target for all the script’s commands. Line three is using the Computers window in netOctopus as the target window for the selection. Line five sets the computer selected in the Computers window as the NT box that needs to have its registry changed. The next line tests to see whether anything is selected in the Computers window. If it is, the next line makes all the modifications to the registry. If not, a dialog box comes up, with the error message we set up in line one.

Short, simple, and very reliable. This is a workhorse script.

Another version of this script in John's tool basket uses netOctopus again, but this time to install Office 97 on a target NT PC. I won't go into a line-by-line explanation of the script, but in general, the error message is similar to the one in the previous script. It also sets up the location of the network drive with the Office 97 install files, the password to be used, and the installation program name. The script asks for the name of the user so that when Office is installed, it’s installed for that user. Next it goes to netOctopus and finds the target computer. Using the Execute PC Installer feature of netOctopus, the installation program starts and passes it a series of parameters, including the username and serial number for the installation. These parameters allow the install to proceed without user intervention until the final phase of the install, and that is only to dismiss the Install Complete dialog box.

Our next script makes use of a quirk with the Execute PC Installer feature of netOctopus—that is, it lets us remotely execute almost any program that can be started from a command line. (This can be a tremendous security hole, but as John notes, good admins always practice safe computing, right?) This script allows John to perform a thorough scan of all the files on a hard drive with Norton AntiVirus, including any files that have been compressed into zip files. The script is almost identical to the Office 97 install script—the only change is the program being run and the parameters that are passed. This is a short script, but it allows John to manually force scans across a network if there’s a new viral outbreak.
property NoSelectionErr : "There is no computer selected. Please select one!"
property theServer : "\\\\Retrospect\\Shared_files"
property thePassword : '********'
property thePath : "C:\\Program Files\\Norton Antivirus"
property theExecutable : "navdx.exe"

tell application "netOctopus"
set theWindow to window "Computers"

set theSelection to selection of theWindow
if theSelection exists then
execute PC installer of theSelection executable path thePath executable theExecutable execute using any drive letter parameter "/L /B+ /M+ /HEUR:3 /S+ /REPAIR /DOALLFILES /ZIPS"
else
display dialog NoSelectionErr buttons {"Okay"} with icon stop
end if
end tell


Our final script is very similar to the NAV script above, except this one uses Norton Disk Doctor to scan a drive and fix any errors it finds:
property NoSelectionErr : "There is no computer selected. Please select one!"
property theServer : "\\\\Retrospect\\Shared_files"
property thePassword : '********'
property thePath : "C:\\Program Files\\Norton Utilities"
property theExecutable : "ndd.exe"

tell application "netOctopus"
set theWindow to window "Computers"

set theSelection to selection of theWindow
if theSelection exists then
execute PC installer of theSelection executable path thePath executable theExecutable execute using any drive letter parameter "/Q /FIXSPACES"
else
display dialog NoSelectionErr buttons {"Okay"} with icon stop
end if
end tell


Conclusion
These simple scripts are invaluable. Other tasks that can be scripted easily are as follows:
  • ·        Creating/changing desktop printer and network configurations
  • ·        “Windowizing” Mac filenames
  • ·        Renaming a large number of files so they have some sort of sequence
  • ·        Changing file types
  • ·        Converting e-mail address book formats

If you prepare and plan adequately, AppleScript can take a lot of the tedium out of your workday. It’s a tireless laborer and has the capability to do almost anything you wish. By using a little caution and care, you can take full advantage of it and free up some time for that vacation you keep meaning to take.

Editor's Picks