System of UNIX of automation of use Perl manages
Tuesday, March 03, 2009 by rain
Government of UNIX system always is an a Gordian knot,It is easy to apply correct tool to be able to make this problem becomes.In this one part,The think of a way that Teodor offerred to simplify to manage with firm system about using Perl.In this kind of environment,Cfengine of systematic configuration engine is an all in all tool.
The exercise in wanting to finish the article,Perl 5.6.0 must be installed in the system.The operating system had better be installation of mainstream UNIX (Linux, Solaris, BSD) the closest version (2000 or update) .The give typical examples in going up to also can use the article with UNIX and other operating system in the Perl of earlier version,But ought to come to possible functional hitch solve as the exercise.
UNIX management has the one big reason that challenges a gender is supplier of every UNIX think the standard is in the light of feebleminded and goofy.So,Even if the operating system of same supplier (SunOS 4.x and Solaris 5.x) also can be essential and different.Below certain circumstance,Do not have a supplier at all even.For example,Linux does not have sole supplier (although Red Hat is the biggest Linux at present,distribute edition) ,The Linux of each version has its original place.If POSIX standardization is done correctly,So it is a measure on the right way that solves this one problem.Regretful is,A when it can make sure systematic government needs a function only small subclass.
What I often say no less than:The tool that understands you.If try to use a kind of tool, language only, or the method does every business,The likelihood is a nightmare.Should have flexibility.
If be put in axiom of a systematic government,That is:After passing twice,Doing not have systematic management job is interesting.If your discovery is repeating,do drab and as dry as a chip thing,So automation it.Of course,Sometimes very hard automation,But should consider this issue at least,The time that and its advantage reachs balance automation place spends.
Cfengine tool
If you are right,automation system government is serious,Should understand socfengine Tool.Aux would rather when you only when spending time in Vi editor,Need not go understandingcfengine .
cfengine It is engine of configuration of a kind of system.It gets configuration script as the input,Act originally according to these feet next.At present version is 1.6.3 (very stable emission edition) ,And version 2.0 also be vividly portrayed.Aboutcfengine The more information of development,Ask a visitcfengine Website (consult please the reference material at the back of the article) .
Must not usecfengine All things that offer you,And you need all things impossibly immediately.At the beginning when,Yourcfengine Configuration document should be very simple,And as discovery more thing hopes automation and grow.
Come fromcfengine Command referenced encyclopedia,There is the most notable character here:
Can monitoring and authority of modification file license and ACL.For example,/ Etc/shadow can keep consistent with authority of 0400/root/sys license,And if those permit authority happening to change,Can warn systematic manager or correct them instantly.According to change of corresponding Fstab,Can be installed automatically and uninstall NFS file.Can manage through onefold file child road of configuration of code of net attack by surprise, DNS, default by and advocate network interface;File and catalog are OK and recursive duplicate to another position,Or this locality is duplicate,Or duplicates from long-range server.Can edit (this isSpecialPowerful character,Offerred criterion expression and overall situation search / to replace) , cycle (for example,Log file) or delete a file.Can link a file (all onefold documents that issue with / or catalog or with criterion the document that expression matchs) with whole catalog.In can be being expressed according to the process criterion of expression match will start, kill, restart process or send aleatoric signal.Can run aleatoric command.Afore-mentioned all these are mixed according to operating system type edit a day of version, medium time, aleatoric user defines kind, of the file in the file, catalog or data have notting have can be conditional etc.
Although use Perl to be able to be donecfengine All businesses that do,Why should begin from the beginning?For example,If want to replace a certain word with another word,Compiling a document can be a simple procedure.The subclass that should begin to allow a system, logistic system part and all other are miscellaneous when the element,A type of local school in ancient times of this one travel can become 300 to go.Why be absentcfengine Do in?It generates the configuration code with 100 readable travel.
According to the experience of myself,Because can begin from file of the smallest configuration,Elapse as time next progressively ground tocfengine Add something,So willcfengine Introducing a site is very easy.Like abrupt change without the person,All system manager is more such (because if anything makes mistake,Ground of their of course can get accusing) .
Configure file management
Managing configuration file is difficult.Can pass a considerationcfengine Whether be competent this task begins.Regretful is,cfengine the editor is to face of travel,So it may suit complex configuration file not quite.But pack to be like TCP implement configuration file / Etc/hosts.allow is in that way simple filecfengine Be suit most.
Normally,The many version that hope reservation configures a file.For example,The likelihood needs to be in / there are two groups of DNS to configure a setting in Etc/resolv.conf,One group is at exterior machine with,Another group is to be used at in-house machine.Very natural,Exterior DNS Resolv.conf can enter the list that calls "external" ,And in-house Resolv.conf can enter corresponding "internal" list.Let us assume these two catalog are below catalog of "spec" of an overall situation,The catalog of a kind of root that this catalog is configuration file.
Following code can all over catalog of all previous Spec,The search agrees with the file name that gives a machine.It will from / Usr/local/spec begins,Next downward,Seek the document that matchs with the request.And,The name that it will check every list whether with what belong to certain machine kind identical.Because of this,If we requestlocate_global('resolv.conf', 'wonka') ,This function will be in / Resolv.conf file is searched below Usr/local/spec catalog,This file or falls in root catalog,Or falls in the subdirectory of this catalog,Kind of photograph that its name should belong to with place of "wonka" machine match.So,If "wonka" belongs to "chocolate" kind,And if have / Usr/local/spec/chocolate/resolv.conf file,Solocate_global() Will return "/usr/local/spec/chocolate/resolv.conf" .
Http://127.0.0.1:8080/developerworks/cn/linux/sdk/perl\culture-5/index.shtmllocate_global() Find the many version that match with file photograph (for example,/ Usr/local/spec/chocolate/resolv.conf and / Usr/local/spec/resolv.conf) ,Criterion it can abandon.One of wronger than having two is close friends was not configured suppose here.Still have,Notice please,The machine can be belonged to more than kind.
Can compose builds such structure.For example,
/ Usr/local/spec/external/chocolate/resolv.conf /usr/local/spec/internal/chocolate/resolv.conf /usr/local/spec/external/sugar/resolv.conf /usr/local/spec/internal/sugar
Will include exterior the file with in-house "chocolate" and "sugar" machine.Need to be installed correctly onlyyour machine_belongs_to_class() Function.
Oncelocate_global() Return name of a file,Using it Scp or Rsync to duplicate to long-range system is quite simple.Remember please,The permissive advantageous position that always should hold this file and attribute."-p" of Scp need indicates,"-a" of Rsync need indicates.Consult the document that wants to use is duplicate jussive documentation.The configuration file that had to unite so is cultivated.
Detailed list 1:Spec catalog alls over all previous
# {{{ locate_global: use spec directory to find a file matching the current class
sub locate_global($$)
{
# this code uses File::Find
my $spec_dir = '/usr/local/spec';
my $file = shift || return undef; # file name sought
my $machine = shift || return undef; # machine name
my @matches;
my $find_sub =
sub
{
print "found file $_\n";
push @matches, $File::Find::name if ($_ eq $file);
# the machine_belongs_to_class sub returns true if a machine
# belongs to a class; we stop traversing down otherwise
$File::Find::prune = 1 unless
machine_belongs_to_class($machine, $_) || $_ eq '.';
};
find($find_sub, $spec_dir);
if (scalar @matches %26gt; 1)
{
print "More than one match for file $file,",
"machine $machine found: @matches\n" ;
return undef;
}
elsif (scalar @matches == 1)
{
return $matches[0]; # this is the right match
}
else {
return undef; # no files found
}
}
# }}}
Once built this to plant / a problem of Usr/local/spec structure is:How do we know Resolv.conf ought to be entered / Etc?The beautiful hierarchy that or did not show like here,Adapt it (for example,Replace "/" with "+" - of a kind of danger with a bit deformed method) ,The map that or carries alone between link name and real name.For example,"The link name that Root-profile" can be "~root/.profile" .Last kinds of method,Also be the method that I like,As a result of name of its tile file and eliminated have the problem that conceals file name.Below structure of a catalog,Each appearance is visible and neat.Of course,Every time when adding the file list,Need does a few works more.The program must know "resolv.conf" should be duplicate to the "/etc/resolv.conf" of long-range system,And "dfstab" should enter "/etc/dfs/dfstab" (the Solaris file that shares system of NFS file) .
Once install hierarchy of Spec catalog,It is OK to let us discuss now what to do.If want to do,The user that can search all names to be Joe:
Detailed list 2:Search file of all Password and find out Joe with Grep
grep Joe `find /usr/local/spec -name passwd`
Perhaps can use a tool,Like Rep.pl (catenary receives Rep.pl) ,Write by David Pitts,Will replace each word with another word:
Detailed list 3:Search file of all Host and change "wonka" "willy "
find /usr/local/spec -name hosts -exec rep.pl wonka willy {} \;
Now,If be willing,Can compile detailed list with Perl 2 and 3;find2perl The utility program that writes for this namely.Although it is very simple,From begin to be used onlyfind .It is wonderful utility program really,Every system manager should be used.More important is,Wrote these two detailed list to spend my 5 only minute.How is understanding usedfind2perl ,The code that generates it stores in the file,Run this file next,How long wanting a flower?Oneself have a try!
Task automation
Task automation is one very the theme of extensive.I am confined to this section be not jussive of seesaw pattern UNIX simple automation.To automation of seesaw pattern jussive,Expect is current practicable best tool.Should the grammar that or understands it,Or uses PerlExpect.pm Module.Can get from CPANExpect.pm ;Consult please reference material in order to know more and detailed information.
Usecfengine ,Can according to aleatoric standard automation almost any tasks.But,Its function function of special elephant Makefile,It is very unmanageable to variable complex operation.When discovery need runs such command,This jussive parameter comes from when be listed at coming loose or passing sole function,Normally best switch arrives Shell script or Perl.As a result of the function of Perl,Its may be better choice.Although,Should not abandon Shell script will use to replace.Sometimes,Perl is needless,You need to run a few simple commands only.
Adding an user automatically is a common problem.The Adduser.pl script that can write oneself,The Adduser program that perhaps offers with system of most contemporary UNIX.Ensure the grammar between system of use all UNIX is to agree please,But do not try to write an interface of general Adduser program.It is too difficult,Thought to cover in you after all UNIX are aberrant,Meet sooner or later somebody asks Win32 or MacOS version.This is not one of problems that can solve with Perl merely,Unless you are special ambitious.Script just lets enquire user name, password here, advocate catalog is waited a moment,And withsystem() Call will call Adduser.
Detailed list 4:Call Adduser with simple script
#!/usr/bin/perl -w
use strict;
my %values; # will hold the values to fill in
# these are the known adduser switches
my %switches = ( home_dir =%26gt; '-d', comment =%26gt; '-c', group =%26gt; '-G',
password =%26gt; '-p', shell =%26gt; '-s', uid =%26gt; '-u');
# this location may vary on your system
my $command = '/usr/sbin/adduser ';
# for every switch, ask the user for a value
foreach my $setting (sort keys %switches, 'username')
{
print "Enter the $setting or press Enter to skip: ";
$values{$setting} = ;
chomp $values{$setting};
# if the user did not enter data, kill this setting
delete $values{$setting} unless length $values{$setting};
}
die "Username must be provided" unless exists $values{username};
# for every filled-in value, add it with the right switch to the command
foreach my $setting (sort keys %switches)
{
next unless exists $values{$setting};
$command .= "$switches{$setting} $values{$setting} ";
}
# append the username itself
$command .= $values{username};
# important - let the user know what's going to happen
print "About to execute [$command]\n";
# return the exit status of the command
exit system($command);
Another when will handle with Perl common task is monitoring is mixed the new process that start.Normally,This is to useProc::ProcessTable CPAN module undertakes,It browses whole process to express,The process list that returns an user to take a lot of principal property.However,Here,I must be recommendedcfengine .Than with look of quick Perl tool,It offerred better process monitoring and the option of the new process that start.If you want to write such tool,So the business that this just been doinging others (andcfengine The hub that had stolen you is built) .If as a result of individual reason,Do not want to usecfengine ,The accessary Pgrep in considering system of most contemporary UNIX and Pkill utility program.pkill -HUP inetd Will use the business that a concise command can do four or place of script of more travel Perl does.This that is to say,If be in,the process monitoring that do is very complex or sensitive to time,Should use Perl clearly so.
For integrality cause,Here is one demonstrated how to be usedkill() Of Perl functionProc::ProcessTable Give typical examples."9" serves as parameter,It is the strongestkill() Parameter,Mean roughly " without giving thought to three seven two ten one,Kill a process to say again " .Do not run this command with Root,Unless want to kill Inetd process really.
Detailed list 5:The process that all over all previous,Kill all Inetd next
use Proc::ProcessTable;
$t = new Proc::ProcessTable;
foreach $p (@{$t-%26gt;table})
{
# note that we will also kill "xinetd" and all processes
# whose command line contains "inetd"
kill 9, $p-%26gt;pid if $p-%26gt;cmndline =~ 'inetd';
}
Last word
UNIX system manages most the part of disappointment letting a person is all sorts of way that UNIX supplier escapes a standard and find.As a result of this kind of reason,When Perl handles all issues in UNIX system alone,It is helpless.If do not have an elephantcfengine Such tool,As syntactic as password file, share a file system and dog the problem such as the log becomes very quickly cannot manage.However,Still put in a few hopes;After all,We just examined Perl to be able to simplify a few methods of systematic government.
Perl andcfengine Be united in wedlock very well.Can generate with Perl custom-builtcfengine Configuration,OK perhaps fromcfengine Script of moving Perl.I had used this both,Discovery is compositive not difficult.However,cfengine Suffer beyond the mark and simple configuration language and effect of devoid data structure.My general is in aboutcfengine this one issue launchs in prospective article.
If choose to come true,The strategy of centralized configuration file of article intermediary carry on ought to be very practical.Had used six months now on my site,And scored huge success.If will complete hierarchy check is like CVS into,in that way version controls a system,The advantage that you still will enjoy version to turn systematic document,Can arrive in order to reply already the either state that check controls a system into version.
Textual link:Http://www-128.ibm.com/developerworks/cn/linux/sdk/perl/culture-5/index.html