WEB开发网
开发学院操作系统Linux/Unix Linux下计算文件的MD5值 阅读

Linux下计算文件的MD5值

 2012-11-28 15:30:15 来源:WEB开发网   
核心提示:#如果是新添加的文件则输出出来其3个时间值,atime mtime ctime sub compareWithLastMD5File { find(\&wantedHash,@_); my $md5file = $ARGV[2]; open MD5FILE,"<","$md5file
#如果是新添加的文件则输出出来其3个时间值,atime mtime ctime
sub compareWithLastMD5File {
find(\&wantedHash,@_);
my $md5file = $ARGV[2];

open MD5FILE,"<","$md5file" or die "Can't read $md5file : $!\n";
my $lastMD5Filerecords = (@lastMD5FilerecordsArray = <MD5FILE>);
my %lastMD5Hash = map { split } @lastMD5FilerecordsArray;
close MD5FILE;

foreach (keys %thisMD5Hash) {
$thisMD5Filerecords++;
}

if ($thisMD5Filerecords >= $lastMD5Filerecords) {
%hash1 = %thisMD5Hash;
%hash2 = %lastMD5Hash;
} else {
%hash1 = %lastMD5Hash;
%hash2 = %thisMD5Hash;
}

foreach (keys %hash1) {
if (exists $hash2{$_}) {
if ( $hash1{$_} ne $hash2{$_} ) {
($atime,$mtime,$ctime) = &getFileAMCTime($_);
print "Different:$_ $hash1{$_} Atime:$atime Mtime:$mtime Ctime:$ctime\n";
}
} else {
if (-e $_) {
($atime,$mtime,$ctime) = &getFileAMCTime($_);
print "Added:$_ $hash1{$_} Atime:$atime Mtime:$mtime Ctime:$ctime\n";
} else {
print "Deleted:$_ $hash1{$_}\n";
}
}
}
}

#比较2个生成的MD5文件(对同一个目录生成的),找出不同的或者不存在的
sub compareWithTwoMD5Files {
my ($md5file1,$md5file2) = ($ARGV[1],$ARGV[2]);
open MD5FILE1,"<","$md5file1" or die "Can't read $md5file1 : $!\n";
open MD5FILE2,"<","$md5file2" or die "Can't read $md5file2 : $!\n";
my $file1record = (@file1record = <MD5FILE1>);
my $file2record = (@file2record = <MD5FILE2>);
close MD5FILE1;
close MD5FILE2;

my %hashmap1 = map { split } @file1record;
my %hashmap2 = map { split } @file2record;

if ($file1record >= $file2record) {
%hash1 = %hashmap1;
%hash2 = %hashmap2;
} else {
%hash1 = %hashmap2;
%hash2 = %hashmap1;
}

foreach (keys %hash1) {
if (exists $hash2{$_}) {
if ( $hash1{$_} ne $hash2{$_} ) {
($atime,$mtime,$ctime) = &getFileAMCTime($_);
print "Different:$_ $hash1{$_} Atime:$atime Mtime:$mtime Ctime:$ctime\n";
}
} else {
if (-e $_) {
($atime,$mtime,$ctime) = &getFileAMCTime($_);
print "Added:$_ $hash1{$_} Atime:$atime Mtime:$mtime Ctime:$ctime\n";
} else {
print "Deleted:$_ $hash1{$_}\n";
}
}
}
}

#遍历条件,找到之后输出
sub wantedPrint {
if (-f $_ && -R $_) {
print "$File::Find::name ",&getMD5($_),"\n";
}
}

#遍历条件,找到之后形成一个HASH
sub wantedHash {
if (-f $_ && -r $_) {
$thisMD5Hash{$File::Find::name} = &getMD5($_);
}
}

#计算MD5值
sub getMD5 {
my $file = shift @_;
open(FH, $file) or die "Can't open '$file': $!\n";
binmode(FH);
my $filemd5 = Digest::MD5->new->addfile(FH)->hexdigest;

Tags:Linux 计算 文件

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接