The author of the translation
messerr , he was just unlucky with karma.
Introduction
As a system administrator, you face many problems. Managing users, disk space, processes, devices, and backups can cause hair loss, humor, or sanity for many administrators. Shell scripts can help out, but they often have many limitations. In this case, a full-featured scripting language, such as Python, can turn a tedious task into an easy and fun, I dare say.
The examples in this article demonstrate the various features of Python that you can use in practice. If you work with them, you are on the right path to understanding the power of Python.
About modules
Module is an important concept in Python. Essentially, a module is a resource that you connect to a program to use later. This process can be compared with the fact that you take out a sheet of paper from a drawer and place it on your desk, thus preparing it for further use. Modules are connected using the
import command, which is present at the beginning of each example. Modules are available for communication with databases, network programming, operating system services and hundreds of other useful areas.
Making Python work
Python is a full-featured, reliable programming language and, in essence, has a lot of features. Studying it can be a task of epic proportions. However, remember that many abilities, such as GUI tools, are of low value to the system administrator. That is why this article uses specific examples: they demonstrate the skills needed to effectively write system management scripts.
')
A little bit about examples:
- Each example uses try: and except: with a block of code inside. It performs elementary error handling. Python has extensive support for handling all kinds of exceptions, but, in the examples of this article, I did a simple check.
- These examples were tested using Python 2.5 running on the Linux® box, but they should work on any Unix / Linux machine.
You will undoubtedly think about improving these scripts. It's good! The nature of Python scripts is that they can be easily modified and configured without the need for recompilation.
Example 1: Search for files and display permissions in a friendly format.The first example (Listing 1) searches for files according to a pattern (which the user enters) and displays the result on the screen along with the permissions for each file. First, you might think that this program does nothing more than invoking the find command; however, it displays the results in a special way and your options for displaying this advanced search are endless.
The script essentially solves three problems:
- Get search pattern from user
- Performs a search
- Shows results to user
When writing a script, constantly ask yourself the question, “What task does this code provide?” By asking yourself this question, you increase attention in your work and its effectiveness.
Listing 1. Search for files and display results with permissions.# -*- coding: utf-8 -*-
import stat, sys, os, string, commands
# ,
try:
pattern = raw_input(" :\n")
# 'find'
commandString = "find " + pattern
commandOutput = commands.getoutput(commandString)
findResults = string.split(commandOutput, "\n")
#
print ":"
print commandOutput
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, " ", perm, " "
else:
print level, " ", perm, " "
except:
print " ! ."
The program follows the steps of:
- Prompts user for a search pattern (lines 7-9).
- Prints a list of found files (lines 12-14).
- Using the stat module, obtains access rights for each found file and displays them on the screen (lines 15-23).
The result of the program is shown in Listing 2.
$ python example1.py
Enter the file pattern to search for:
j*.py
Listing 2. Displaying the first example$ python example1.py
:
j*.py
:
jim.py
jim2.py~
================================
Permissions for file jim.py :
USR R
USR W
USR X
GRP R
GRP W
GRP X
OTH R
OTH W
OTH X
Permissions for file jim2.py :
USR R
USR W
USR X
GRP R
GRP W
GRP X
OTH R
OTH W
OTH X
Example 2: Running a tar archive using the menuThe previous example for its work requested a search pattern from the user. Another way to get information from the user is the command line argument. The program in Listing 3 shows how to do this in Python: the code takes the name of the tar file as a command-line argument and then offers several options to the user. This example also shows a new way to solve the problem. The first example used the command module to run
find and capture the output. This approach can be called clumsy and not very “Pythonite”. This example uses the
tarfile module to open a tar file, the advantage of which is that it allows you to use Python attributes and methods when manipulating files. With the help of many Python modules, you can do things that are not available through the command line. This is a good example of using the menu in Python. The program performs various actions depending on your choice:
- If you press 1, the program will offer to select a file in the archive for extraction into the current directory and then extract the file.
- If you press 2, the program prompts you to select a file and then displays information about it.
- If you press 3, the program will list all the files in the archive.
Listing 3. Running a tar archive using the menu# -*- coding: utf-8 -*-
import tarfile, sys
try:
# tar-
tar = tarfile.open(sys.argv[1], "r:tar")
#
selection = raw_input("\n\
1 \n\
2 \n\
3 \n\n")
# ,
if selection == "1":
filename = raw_input(" : ")
tar.extract(filename)
elif selection == "2":
filename = raw_input(" : ")
for tarinfo in tar:
if tarinfo.name == filename:
print "\n\
:\t\t", tarinfo.name, "\n\
:\t\t", tarinfo.size, "\n"
elif selection == "3":
print tar.list(verbose=True)
except:
print " !"
The program follows the steps of:
- Opens the tar file (line 5).
- Displays the menu and gets the user's choice (lines 8-11).
- If you pressed 1 (lines 14-16), it extracts the file from the archive.
- If you pressed 2 (lines 17-23), provides information about the selected file.
- If you pressed 3 (lines 24-25), it provides information about all files in the archive.
The result of the program is shown in Listing 4.
Listing 4. User menu for the second sample$ python example2.py jimstar.tar
1
2
3
Example 3. Checking the running process and displaying information in a friendly view.One of the most important duties of a system administrator is to check running processes. The script in Listing 5 will give you some ideas. The program takes advantage of Unix features: the
grep command uses output generated by another command. This will allow you to reduce the amount of data that Python will analyze further.
The program also uses the
string module. Explore this module - you will use it often.
Listing 5. Displaying information about the running process in a friendly view# -*- coding: utf-8 -*-
import commands, os, string
program = raw_input(" : ")
try:
# 'ps'
output = commands.getoutput("ps -f|grep " + program)
proginfo = string.split(output)
#
print "\n\
:\t\t", proginfo[5], "\n\
:\t\t\t", proginfo[0], "\n\
ID :\t\t", proginfo[1], "\n\
ID :\t", proginfo[2], "\n\
:\t\t", proginfo[4]
except:
print " !"
The program follows the steps of:
- Gets the name of the process to check and assigns it to a variable (line 3).
- Runs the ps command and adds the result to the list (lines 7-8).
- Displays detailed information about the process (lines 11-16).
- The output of the program is shown in Listing 6.
Listing 6. Displaying the third example$ python example3.py
: xterm
: pts/0
: goga
ID : 26509
ID : 26493
: 17:28
Example 4. Checking usernames and passwords for security policy compliance. Security management is an important part of the job for every system administrator. Python makes this work easier, as the last example shows. The program in Listing 7 uses the
pwd module to access the password database. It checks user names and passwords for compliance with the security policy (in this case, the names must be at least 6 characters in length, passwords - 8 characters). There are two caveats:
This program only works if you have full rights to access / etc / passwd.
If you use shadow passwords, the script will not work (however, in Python 2.5 there is a
spwd module that will solve this problem).
Listing 7. Checking usernames and passwords for security policy compliance# -*- coding: utf-8 -*-
import pwd
#
erroruser = []
errorpass = []
#
passwd_db = pwd.getpwall()
try:
#
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)
#
print " 6 :"
for item in erroruser:
print item
print "\n 8 :"
for item in errorpass:
print item
except:
print " !"
The program follows the steps of:
- Initializes the lists of counters (lines 4-5).
- Opens the password database and writes the data to the list (line 8).
- Checks usernames and passwords for validity (lines 12-18).
- Displays names and passwords that do not comply with the security policy (lines 21-26).
The result of the program is shown in Listing 8.
Listing 8. Conclusion of the fourth example$ python example4.py
6 ::
Guest
8 :
Guest
johnsmith
joewilson
suejones
Another use of scripts. You can use Python in a number of ways to control the system. One of the best things you can do is analyze your work, determine which tasks you perform repeatedly, and study the Python modules that will help you solve these problems - almost certainly, there are those. Some areas where Python can be a great helper:
- Server management: check patches for a specific application and update them automatically.
- Logging: automatically sending an e-mail when a special type of error appears in the logs.
- Network: create a Telnet connection to the server and monitor the connection status.
Testing web applications: using freely available tools for emulating a web browser and testing a web application for functionality and performance.
These are just a few examples - I am sure you can add your own useful ideas to them.
Summary
With its ease of learning, its ability to manage files, processes, strings and numbers, and its almost endless array of utility modules, Python is a scripting language that looks like it was created specifically for system administrators. Python is a valuable tool in the toolkit of any system administrator.