Professional Documents
Culture Documents
Adopt Python to manage UNIX® systems while incorporating concepts of good program
design. Python is an easy-to-learn, open source scripting language that lets system
administrators do their job more quickly. It can also make tasks more fun.
Introduction
As a system administrator, you run across numerous challenges and problems. Managing users,
disk space, processes, devices, and backups can cause many system administrators to lose their
hair, good humor, or sanity. Shell scripts can help, but they often have frustrating limitations. This is
where a full-featured scripting language, such as Python, can turn a tedious task into an easy and,
dare I say it, fun one.
The examples in this article demonstrate different Python features that you can put to practical
use. If you work through them, you'll be well on your way to understanding the power of Python.
About modules
A module is an important Python concept. Basically, a module is a resource you import in order to
use it. This process is comparable to taking a piece of paper out of a file cabinet and putting it on
your desk, ready for use. You import modules using the import command, which appears at the
top of each of the example programs. Modules are available for database connectivity, network
programming, operating system services, and hundreds of other useful areas.
• It's mature. Python has been around a long time, which means its code is stable, lots
of modules add functionality, and robust documentation is available on the Web.
Python is a full-featured, robust programming language and, as such, it has tons of features.
Learning it could be a task of epic proportions. However, remember that many Python features,
such as the GUI toolkits, are of limited value to system administrators. That's why this article uses
specific examples: They demonstrate the skills you need to effectively write Python scripts to
manage systems.
Listing 1. Search for files and list results with file permissions
import stat, sys, os, string, commands
try:
#run a 'find' command and assign results to a variable
pattern = raw_input("Enter the file pattern to search for:\n")
commandString = "find " + pattern
commandOutput = commands.getoutput(commandString)
findResults = string.split(commandOutput, "\n")
print "================================"
for file in findResults:
mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE])
print "\nPermissions for file ", file, ":"
for level in "USR", "GRP", "OTH":
for perm in "R", "W", "X":
if mode & getattr(stat,"S_I"+perm+level):
print level, " has ", perm, " permission"
else:
print level, " does NOT have ", perm, " permission"
except:
print "There was a problem - check the message above"
When the program is run, the output looks like that shown in Listing 2.
how to do that in Python: The code takes a tar filename as a command-line argument and then
prompts the user with several options.
This example also shows a new way to attack the problem. The first example used the command
module to run the find command and capture the output. This approach can be clumsy and isn't
very "Pythonic." This example uses the tarfile module to open a tar file, which has the advantage of
allowing you to use Python attributes and methods as you manipulate the file. With many modules
provided by Python, you can do things that can't be done through the command line.
This is a good example of implementing a menu system in Python. The program performs different
actions based on your selection:
• If you press 1, the program prompts you for the file name in the archive to extract the current
directory to and then extracts the file.
• If you press 2, the program prompts you for the file name and then displays the file
information.
• If you press 3, the program lists all the files in the archive.
try:
#open tarfile
tar = tarfile.open(sys.argv[1], "r:tar")
This program also uses the string module. Get to know this module—you'll use it often.
try:
#perform a ps command and assign results to a list
output = commands.getoutput("ps -f|grep " + program)
proginfo = string.split(output)
#display results
print "\n\
Full path:\t\t", proginfo[5], "\n\
Owner:\t\t\t", proginfo[0], "\n\
Process ID:\t\t", proginfo[1], "\n\
Parent process ID:\t", proginfo[2], "\n\
Time started:\t\t", proginfo[4]
except:
print "There was a problem with the program."
1. Get the name of a process to check and assign it to a variable (line 3).
2. Run the ps command and assign the results to a list (lines 7-8).
3. Display detailed information about the process with English terms (lines 11-16).
The output is shown in Listing 6.
The program in Listing 7 uses the pwd module to access the password database. It checks userids
and passwords for security policy compliance (in this case, that userids are at least six characters
long and passwords are at least eight characters long).
Listing 7. Check userids and passwords for compliance with security policy
import pwd
#initialize counters
erroruser = []
errorpass = []
try:
#check each user and password for validity
for entry in passwd_db:
username = entry[0]
password = entry [1]
if len(username) < 6:
erroruser.append(username)
if len(password) < 8:
errorpass.append(username)
Some specific areas where Python can be of great help are as follows:
• Managing servers: Checks patch levels for a particular application across a set of servers
and updates them automatically.
• Logging: Sends an e-mail automatically if a particular type of error shows up in the syslog.
• Networking: Makes a Telnet connection to a server and monitors the status of the
connection.
• Testing Web applications: Uses freely available tools to emulate a Web browser and verifies
Web application functionality and performance.
These are just a few examples—I'm sure you can add useful ideas of your own.
Summary
With its easy-to-learn language; its ability to handle files, processes, strings, and numbers; and its
almost endless array of helper modules, Python is a scripting language that looks like it was made
for system administrators. It's a valuable tool for any system administrator's toolbox.
Related topics
• The Python tutorial: This tutorial is a great source of basic language information.
• "Discover Python" (Robert J. Brunner, developerWorks): Read all the articles in the
developerWorks "Discover Python" series.
• Official Python Web site: This site provides a wealth of information and downloads.
• The Python Cookbook: This site is maintained by ActiveState and is a user community with
user-contributed scripts on virtually every programming topic.
• Planet Python: This site covers all things Python.
• AIX and UNIX: The AIX and UNIX developerWorks zone provides a wealth of information
relating to all aspects of AIX systems administration and expanding your UNIX skills.
• Search the AIX and UNIX library by topic:
• System administration
• Application development
• Performance
• Porting
• Security
• Tips
• Tools and utilities
• Java™ technology
• Linux
• Open source
• IBM trial software: Build your next development project with software for download directly
from developerWorks.
• Browse the Python section of the Safari Technology Bookstore for books on these and other
technical topics.
• Download the latest version of Python.