2008年(5)
分类: LINUX
2008-03-27 11:23:03
原文出处:http://www.ibm.com/developerworks/aix/library/au-satsystemvalidity/index.html
#!/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 record\n";
}
}
sub loadchksumdata
{
my ($file) = @_;
open(DATA,$file) or die "Cannot open check sum file $file: $!\n";
while()
{
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 record\n";
gendiffreport($chksumdata->{$name}, $fileinfo);
}
delete($chksumdata->{$name});
}
else
{
print STDERR "Warning: Couldn't find $name in existing records\n";
}
}
else
{
printf $outfile ("%s\n",$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{
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]));
}
$ genmd5.pl --basedir=/etc --chksumfile=etc-chksum.dat