⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 psa-chapter05.txt

📁 perl语言的经典文章
💻 TXT
📖 第 1 页 / 共 2 页
字号:
Example code from Perl for System Administration by David N. Blank-Edelman
O'Reilly and Associates, 1st Edition, ISBN 1-56592-609-9

Chapter Five
============
#*
#* one way to parse a host file
#*

open(HOSTS, "/etc/hosts") or die "Unable to open host file:$!\n";
while (defined ($_ = <HOSTS>)) {
    next if /^#/;  # skip comments lines
    next if /^$/;  # skip empty lines
	 s/\s*#.*$//;  # delete in-line comments and preceding whitespace
    ($ip, @names) = split;
	 die "The IP address $ip already seen!\n" if (exists $addrs{$ip});
    $addrs{$ip} = [@names];
    for (@names){
	 die "The host name $_ already seen!\n" if (exists $names{$_});
         $names{$_} = $ip;
    }
}
close(HOSTS);
-------
#*
#* generate a host file from a machine database
#*

$datafile ="./database";
$recordsep = "-=-\n";

open(DATA,$datafile) or die "Unable to open datafile:$!\n";

$/=$recordsep; # prepare to read in database file one record at a time

print "#\n\# host file - GENERATED BY $0\n# DO NOT EDIT BY HAND!\n#\n";
while (<DATA>) {
    chomp;                           # remove the record separator
    # split into key1,value1,...bingo, hash of record
    %record = split /:\s*|\n/m; 
    print "$record{address}\t$record{name} $record{aliases}\n";
}
close(DATA);
-------
#*
#* generate host file from machine database with error checking added
#*

$datafile ="./database";
$recordsep = "-=-\n";

open(DATA,$datafile) or die "Unable to open datafile:$!\n";

$/=$recordsep; # prepare to read in database file one record at a time

print "#\n\# host file - GENERATED BY $0\n# DO NOT EDIT BY HAND!\n#\n";
while (<DATA>) {
    chomp;  # remove the record separator
    # split into key1,value1,...bingo, hash of record
    %record = split /:\s*|\n/m; 

    # check for bad hostnames
    if ($record{name} =~ /[^-.a-zA-Z0-9]/) {
	    warn "!!!! $record{name} has illegal host name characters,
              skipping...\n";
	    next;
    }

    # check for bad aliases
    if ($record{aliases} =~ /[^-.a-zA-Z0-9\s]/) {
	    warn "!!!! $record{name} has illegal alias name characters,
              skipping...\n";
	    next;
    }

    # check for missing address
    if (!$record{address}) {
	    warn "!!!! $record{name} does not have an IP address,
              skipping...\n";
	    next;
    }

    # check for duplicate address
    if (defined $addrs{$record{address}}) {
	    warn "!!!! Duplicate IP addr: $record{name} &
              $addrs{$record{address}}, skipping...\n";
	    next;
    }
    else {
	    $addrs{$record{address}} = $record{name};
    }

    print "$record{address}\t$record{name} $record{aliases}\n";
}
close(DATA);
-------
#*
#* generating host file from machine database with prettier output
#*
$datafile ="./database";

# get username on either WinNT/2000 or UNIX
$user = ($^O eq "MSWin32")? $ENV{USERNAME} :
                            (getpwuid($<))[6]." (".(getpwuid($<))[0].")";

open(DATA,$datafile) or die "Unable to open datafile:$!\n";

$/=$recordsep; # read in database file one record at a time

while (<DATA>) {
    chomp;                           # remove the record separator
    # split into key1,value1
    @record = split /:\s*|\n/m; 

    $record ={};                     # create a reference to empty hash
    %{$record} = @record;            # populate that hash with @record

    # check for bad hostname
    if ($record->{name} =~ /[^-.a-zA-Z0-9]/) {
	    warn "!!!! ".$record->{name} .
                 " has illegal host name characters, skipping...\n";
	    next;
    }

    # check for bad aliases
    if ($record->{aliases} =~ /[^-.a-zA-Z0-9\s]/) {
	    warn "!!!! ".$record->{name} .
                 " has illegal alias name characters, skipping...\n";
	    next;
    }

    # check for missing address
    if (!$record->{address}) {
	    warn "!!!! ".$record->{name} .
             " does not have an IP address, skipping...\n";
	    next;
    }

    # check for duplicate address
    if (defined $addrs{$record->{address}}) {
	    warn "!!!! Duplicate IP addr:".$record->{name}.
                 " & ".$addrs{$record->{address}}.", skipping...\n";
	    next;
    }
    else {
	    $addrs{$record->{address}} = $record->{name};
    }

    $entries{$record->{name}} = $record; # add this to a hash of hashes
}
close(DATA);

# print a nice header
print "#\n\# host file - GENERATED BY $0\n# DO NOT EDIT BY HAND!\n#\n";
print "# Converted by $user on ".scalar(localtime)."\n#\n";

# count the number of entries in each department and then report on it
foreach my $entry (keys %entries){
    $depts{$entries{$entry}->{department}}++;
}
foreach my $dept (keys %depts) {
    print "# number of hosts in the $dept department: $depts{$dept}.\n";
}
print "# total number of hosts: ".scalar(keys %entries)."\n#\n\n";

# iterate through the hosts, printing a nice comment and the entry itself
foreach my $entry (sort byaddress keys %entries) {
    print "# Owned by ",$entries{$entry}->{owner}," (",
          $entries{$entry}->{department},"): ",
          $entries{$entry}->{building},"/",
          $entries{$entry}->{room},"\n";
    print $entries{$entry}->{address},"\t",
          $entries{$entry}->{name}," ",
          $entries{$entry}->{aliases},"\n\n";
}

sub byaddress {
   @a = split(/\./,$entries{$a}->{address});
   @b = split(/\./,$entries{$b}->{address});
   ($a[0]<=>$b[0]) ||
   ($a[1]<=>$b[1]) ||
   ($a[2]<=>$b[2]) ||
   ($a[3]<=>$b[3]);
}
-------
#*
#* generating host file from machine database with RCS support added
#*
$outputfile="hosts.$$"; # temporary output file
$target="hosts";        # where we want the converted data stored

$datafile ="./database";

# get username on either WinNT/2000 or UNIX
$user = ($^O eq "MSWin32")? $ENV{USERNAME} :
                            (getpwuid($<))[6]." (".(getpwuid($<))[0].")";

open(DATA,$datafile) or die "Unable to open datafile:$!\n";

$/=$recordsep; # read in database file one record at a time

while (<DATA>) {
    chomp;                           # remove the record separator
    # split into key1,value1
    @record = split /:\s*|\n/m; 

    $record ={};                     # create a reference to empty hash
    %{$record} = @record;            # populate that hash with @record

    # check for bad hostname
    if ($record->{name} =~ /[^-.a-zA-Z0-9]/) {
	warn "!!!! ".$record->{name} .
             " has illegal host name characters, skipping...\n";
	next;
    }

    # check for bad aliases
    if ($record->{aliases} =~ /[^-.a-zA-Z0-9\s]/) {
	warn "!!!! ".$record->{name} .
             " has illegal alias name characters, skipping...\n";
	next;
    }

    # check for missing address
    if (!$record->{address}) {
	warn "!!!! ".$record->{name} .
	     " does not have an IP address, skipping...\n";
	next;
    }

    # check for duplicate address
    if (defined $addrs{$record->{address}}) {
	warn "!!!! Duplicate IP addr:".$record->{name}.
             " & ".$addrs{$record->{address}}.", skipping...\n";
	next;
    }
    else {
	    $addrs{$record->{address}} = $record->{name};
    }

    $entries{$record->{name}} = $record; # add this to a hash of hashes
}
close(DATA);

open(OUTPUT,"> $outputfile") or 
  die "Unable to write to $outputfile:$!\n";

print OUTPUT "#\n\# host file - GENERATED BY $0\n
              # DO NOT EDIT BY HAND!\n#\n";
print OUTPUT "# Converted by $user on ".scalar(localtime)."\n#\n";

# count the number of entries in each department and then report on it
foreach my $entry (keys %entries){
    $depts{$entries{$entry}->{department}}++;
}

foreach my $dept (keys %depts) {
    print OUTPUT "# number of hosts in the $dept department:
                  $depts{$dept}.\n";
}
print OUTPUT "# total number of hosts: ".scalar(keys %entries)."\n#\n\n";

# iterate through the hosts, printing a nice comment and the entry
foreach my $entry (sort byaddress keys %entries) {
    print OUTPUT 
          "# Owned by ",$entries{$entry}->{owner}," (",
          $entries{$entry}->{department},"): ",
          $entries{$entry}->{building},"/",
          $entries{$entry}->{room},"\n";
    print OUTPUT 
          $entries{$entry}->{address},"\t",
          $entries{$entry}->{name}," ",
          $entries{$entry}->{aliases},"\n\n";
}

close(OUTPUT);

use Rcs;
# where our RCS binaries are stored
Rcs->bindir('/usr/local/bin');  
# create a new RCS object
my $rcsobj = Rcs->new;          
# configure it with the name of our target file
$rcsobj->file($target);
# check it out of RCS (must be checked in already)
$rcsobj->co('-l');
# rename our newly created file into place 
rename($outputfile,$target) or 
  die "Unable to rename $outputfile to $target:$!\n";
# check it in
$rcsobj->ci("-u","-m"."Converted by $user on ".scalar(localtime)); 

sub byaddress {
   @a = split(/\./,$entries{$a}->{address});
   @b = split(/\./,$entries{$b}->{address});
   ($a[0]<=>$b[0]) ||
   ($a[1]<=>$b[1]) ||
   ($a[2]<=>$b[2]) ||
   ($a[3]<=>$b[3]);
}
-------
#*
#* print the contents of the NIS hosts map
#*

use Net::NIS;

# get our default NIS domain name
$domain = Net::NIS::yp_get_default_domain(); 
# grab the map
($status, $info) = Net::NIS::yp_all($domain,"hosts.byname"); 
foreach my $name (sort keys %{$info}){
    print "$name => $info->{$name}\n";
}
-------
#*
#* look up the IP address of a particular hostname in NIS
#*

use Net::NIS;

$hostname = "olaf.oog.org";
$domain = Net::NIS::yp_get_default_domain(); 
($status,$info) = Net::NIS::yp_match($domain,"hosts.byname",$hostname);
print $info,"\n";
-------
#*
#* check that all NIS servers are responding properly
#*

use Net::NIS;

$yppollex = "/usr/etc/yp/yppoll"; # full path to the yppoll executable

$domain = Net::NIS::yp_get_default_domain(); 

($status,$info) = Net::NIS::yp_all($domain,"ypservers");

foreach my $name (sort keys %{$info}) {
    $answer = `$yppollex -h $name hosts.byname`;
    if ($answer !~ /has order number/) {
        warn "$name is not responding properly!\n";
    }
}
-------
#*
#* subroutine to generate DNS configuration file header
#*

# get today's date in the form of YYYYMMDD
@localtime = localtime;
$today = sprintf("%04d%02d%02d",$localtime[5]+1900,
                                $localtime[4]+1,
                                $localtime[3]);

# get username on either NT/2000 or UNIX
$user = ($^O eq "MSWin32")? $ENV{USERNAME} :
                            (getpwuid($<))[6]." (".(getpwuid($<))[0].")";

sub GenerateHeader{
    my($header);

    # open old file if possible and read in serial number     
    # assumes the format of the old file
    if (open (OLDZONE,$target)){
	    while (<OLDZONE>) {
	        next unless (/(\d{8}).*serial/); 
	        $oldserial = $1;
	        last;
	    }
	    close (OLDZONE);
    }
    else {
	$oldserial = "000000"; # otherwise, start with a 0 number
    }
    
    # if old serial number was for today, increment last 2 digits, else 
    # start a new number for today
    $olddate = substr($oldserial,0,6);
    $count = (($olddate == $today) ? substr($oldserial,6,2)+1 : 0);

    $serial = sprintf("%6d%02d",$today,$count);

    # begin the header
    $header .= "; dns zone file - GENERATED BY $0\n";
    $header .= "; DO NOT EDIT BY HAND!\n;\n";
    $header .= "; Converted by $user on ".scalar((localtime))."\n;\n";
    
    # count the number of entries in each department and then report
    foreach my $entry (keys %entries){
        $depts{$entries{$entry}->{department}}++;
    }
    foreach my $dept (keys %depts) {
        $header .= "; number of hosts in the $dept department:            
                    $depts{$dept}.\n";
    }
    $header .= "; total number of hosts: ".scalar(keys %entries)."\n;\n\n";

    $header .= <<"EOH";

@ IN SOA   dns.oog.org. hostmaster.oog.org. (
                           $serial ; serial
                            10800    ; refresh
                            3600     ; retry
                            604800   ; expire
                            43200)   ; TTL

@                           IN  NS  dns.oog.org.

EOH

  return $header;
}
-------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -