MD5-Validated Perl scripts

Source: Internet
Author: User
Tags md5

#!/opt/perl/bin/perl-w

Use strict;

Use DIGEST::MD5 QW (MD5 md5_hex md5_base64);

#校验文件函数
Sub Calc_md5_hex () {
My ($file _name, $ctx, $MD 5);

($file _name) = @_;

Open (FileHandle, $file _name) or die "Can ' t open/' $file _name/': $!";
$ctx = digest::md5->new;
Binmode (FileHandle);
$ctx->addfile (*filehandle) | | Die "$!/n";
$MD 5 = $ctx->hexdigest;
Close FileHandle;

return $MD 5;
}

Sub Calc_md5_ascii () {
My ($file _name, $ctx, $MD 5);

($file _name) = @_;

Open (FileHandle, $file _name) or die "Can ' t open/' $file _name/': $!";
$ctx = digest::md5->new;
#binmode (FileHandle);
$ctx->addfile (*filehandle) | | Die "$!/n";
$MD 5 = $ctx->hexdigest;
Close FileHandle;

return $MD 5;
}

#定义目录路径
My $dirhandle = $ARGV [0];
#my $file _only = $ARGV [1]; #定义是否只是文件测试, to validate a single file call

if (-f $dirhandle) {
My $file _md5;
if (-t $dirhandle) {
$file _md5 = &calc_md5_ascii ($dirhandle);
}elsif (-b $dirhandle) {
$file _md5 = &calc_md5_hex ($dirhandle);
}

Print "Start calculating file MD5 value:/n${dirhandle}/n/t[${file_md5}][md5_hex]/n";

Exit 0;
}elsif (-D $dirhandle) {
My $file _md5;
Print "Start verifying all Files under directory:/n";
Opendir (DH, "$dirhandle") or die "Can ' t oprn dir/' $dirhandle/': $!";

foreach My $file (Readdir DH) {
$file = $dirhandle. ' /'. $file;

if (-f $file) {
Next if ($file =~ m{/.$} | | $file =~ m{/. $} || -L $file);

if (-t $file) {
#print "Calculate md5!/n according to text file";
$file _md5 = &calc_md5_ascii ($file);
Print "Start calculating file MD5 value:/n${file}/n/t[${file_md5}][md5_ascii]/n";
}elsif (-b $file) {
#print "Calculate md5!/n in binary file";
$file _md5 = &calc_md5_hex ($file);
Print "Start calculating file MD5 value:/n${file}/n/t[${file_md5}][md5_hex]/n";
}else{
Print "does not recognize whether the file is binary or text, and calculates!/n in binary file";
$file _md5 = &calc_md5_hex ($file);
Print "Start calculating file MD5 value:/n${file}/n/t[${file_md5}][md5_hex]/n";
}
}
}

Closedir DH;
}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.