13.07.2015 Views

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 1 ■ SAVING YOURSELF EFFORTIdeally, most of your code should be crystal clear without comments (this is where coding practicessuch as sensible variable names come in). But, as with this script, having at least a comment up topsaying what the script does, what input it expects, and what output it provides will be incredibly helpfulat that later date I keep mentioning. (I like to add my initials and the date as well, but that’s optional—itdepends on if you want to know who to blame when something breaks.) Checking for the correctnumber of arguments (as in line 09 of the script later in this recipe) and printing a usage message areboth good ways of making a script self-documenting.If you’re doing anything remotely complex, a line or two of comment never goes amiss. While you’reat it, consider whether you want to turn what you’re doing into a subroutine, as in lines 22 to 26 of thescript—this is another good way of increasing readability and extendibility. In this case, instead of justprinting out the regular users, you could use this subroutine to import them into your LDAP database.See recipes 2-9 to 2-11 for more on LDAP scripting.If you’re wedded to a scripting language other than Perl or bash, there’s no need to skip readingthis—most of it should be of general applicability. So, feel free to substitute $language-name at will.As an example, let’s look at a script that parses /etc/passwd and prints out the regular users (asopposed to the system users), as indicated by whether they have a UID greater than 1,000. Dependingon your setup, this may not be 100 percent accurate; check the output before doing anything permanentwith it!01 #!/usr/bin/perl -w02 # Script to print non-system user lines from /etc/passwd03 # JK 25.03.20090405 use strict;0607 # Declare subroutines before they're used; this one is defined after08 # the main script logic, lines 25-29. You could if you preferred define09 # it here.10 sub printuser;1112 die "Usage: $0" unless @ARGV == 0;1314 my $file = "/etc/passwd";1516 open FILE, $file;17 while ( ) {18 my @userarray = split /:/;19 if ( $userarray[2] && ( $userarray[2] >= 1000 ) ) {20 printuser(@userarray);21 }22 }23 close FILE;2425 sub printuser {26 my @userarray = @_;27 my $userline = join "\t", @userarray;28 print "$userline\n";29 }Lines 01 and 05 demonstrate the single best way to make life easier in Perl. You should put these twolines at the top of every single script you write.8Download at WoweBook.Com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!