系统管理工具包: 测试系统的有效性
2008-11-11 08:12:28 来源:WEB开发网此流程的最后一个阶段是存储信息,并提供将当前信息与存储的信息进行比较的方法。
验证校验和信息
最后一个脚本基于清单 6 中的脚本。该脚本对原始脚本进行了显著扩展,合并了许多新功能:
使用 Getopt::Long 模块分析的命令行选项。这使您能够指定校验和文件(存储您计算的校验和与其他信息)、是否比较新信息和旧信息(通过阅读校验和文件的内容)和指定要搜索的基本目录。如果比较该文件,将会更新数据并仅报告差异。
loadchksumdata() 函数,该函数以方便比较新信息和旧信息的方法加载和分析现有数据文件。
gendiff report() 函数,该函数将所存储信息的各个字段与当前信息进行实际比较,告诉您更改了哪些内容。仅当确定已存在某种差异时,才调用此函数。
清单 8. 最终脚本
#!/usr/local/bin/perl
use Digest::MD5;
use IO::File;
use strict;
use File::Find ();
use Getopt::Long;
my $chksumfile = 'chksums.dat';
my $compare = 0;
my $basedir = '/etc';
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
GetOptions("chksumfile=s" => $chksumfile,
"compare" => $compare,
"basedir=s" => $basedir);
my $chksumdata = {};
if ($compare)
{
loadchksumdata($chksumfile);
}
my $outfile = '';
if (!$compare)
{
$outfile = IO::File->new($chksumfile,"w");
}
File::Find::find({wanted => &wanted}, $basedir);
if ($compare)
{
foreach my $file (keys %{$chksumdata})
{
print STDERR "Couldn't find $file, but have the info on recordn";
}
}
sub loadchksumdata
{
my ($file) = @_;
open(DATA,$file) or die "Cannot open check sum file $file: $!n";
while(<DATA>)
{
chomp;
my ($filename,$rest) = split(/:/,$_,2);
$chksumdata->{$filename} = $_;
}
close(DATA);
}
sub wanted {
next unless (-f $name);
my $fileinfo = genchksuminfo($name);
if ($compare)
{
if (exists($chksumdata->{$name}))
{
if ($chksumdata->{$name} ne $fileinfo)
{
print STDERR "Warning: $name differs from that on recordn";
gendiffreport($chksumdata->{$name}, $fileinfo);
}
delete($chksumdata->{$name});
}
else
{
print STDERR "Warning: Couldn't find $name in existing recordsn";
}
}
else
{
printf $outfile ("%sn",$fileinfo);
}
}
sub gendiffreport
{
my ($orig,$curr) = @_;
my @fields = qw/filename chksum device inode mode nlink uid gid size mtime ctime/;
my @origfields = split(/:/,$orig);
my @currfields = split(/:/,$curr);
for(my $i=0;$i<scalar @origfields;$i++)
{
if ($origfields[$i] ne $currfields[$i])
{
print STDERR "t$fields[$i] differ; was $origfields[$i],
now $currfields[$i]n";
}
}
}
sub genchksuminfo
{
my ($file) = @_;
my $chk = Digest::MD5->new();
my (@statinfo) = stat($file);
$chk->add(@statinfo[0,1,2,3,4,5,7,9,10]);
$chk->addfile(IO::File->new($file));
return sprintf("%s:%s:%s",
$file,$chk->hexdigest,
join(':',@statinfo[0,1,2,3,4,5,9,10]));
}
更多精彩
赞助商链接