举个栗子

马辰龙De技术分享
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

perl 增量、全量备份脚本

Posted on 2016-07-09 14:20  ChenlongMa  阅读(565)  评论(0编辑  收藏  举报

脚本采用json配置文件,可以自定义,备份目录,全量备份周期,增量备份时间等。

JSON配置文件:

{
  "backupDir": "/data_backup",
  "archiveDir": "/archive_dir",
  "original": "/www/",
  "fullDayBase": 10
}

主程序

#!/usr/bin/perl
use warnings;
use File::Copy::Recursive qw/dircopy rcopy/;
use File::Rsync;
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
use JSON;
use File::Basename;
use POSIX qw(strftime);
use Data::Dumper;
my ( $day, $json );
my $backupDate = strftime( "%Y%m%d", localtime(time) );
open JSON, "/sh/rsyncfile/backupconf.json" or die "$!";
$json = $_ while <JSON>;
my $hashRef     = decode_json $json;
my $originalDir = $hashRef->{original};       
#记得加/,不加/ 弹鸡鸡
my $backupDir   = $hashRef->{backupDir};
my $archiveDir  = $hashRef->{archiveDir};
my $fullDayBase = $hashRef->{fullDayBase};    
#全备份周期
 
$day = $1 if $backupDate =~ /(\d{2})$/;
mkdir $backupDir  unless -d $backupDir;
mkdir $archiveDir unless -d $archiveDir;
rsync_dir( $originalDir, $backupDir );        
#同步目录
 
if ( $day % $fullDayBase == 0 ) {             
#判断周期
    for my $zipName ( glob "$backupDir/*" ) {
        my $zipFromDir = basename($zipName);
        $zipName = basename($zipName) . "_" . $backupDate . '.zip';
        print $zipName, "\n";
        zip_dir( $backupDir, $archiveDir, $zipName, $zipFromDir );
    }
}
 
#压缩目录
sub zip_dir {
    my ( $backupDir, $archiveDir, $zipName, $zipFromDir ) = @_;
    my $zip = Archive::Zip->new();
    my $dirMember = $zip->addTree( "$backupDir/$zipFromDir", $zipFromDir ); 
#递归压缩目录
    unless ( $zip->writeToFileNamed("$archiveDir/$zipName") == 0 ) {
        die 'write error';
    }
 
}
 
#同步目录
sub rsync_dir {
    my ( $source, $target ) = @_;
    print "rsync file from $source to $target\n";
 
    
# archive 归档模式
    
# compress 压缩
    
# verbose 打印详细信息
    my $obj = File::Rsync->new(
        { archive => 1, compress => 1, del => 1, verbose => 1 } );
    $obj->exec( { src => $source, dest => $target } )
        or warn "rsync failed\n";
 
    
#输出同步内容
    print $obj->out;
 
}
 
#复制
sub copy {
    my ( $source, $target ) = @_;
    print $source, "\n";
    if ( -d $source ) {
        $File::Copy::Recursive::CPRFComp = 1;
        dircopy( $source, $target ) or die "$!";
    }
    else {
        rcopy( $source, $target ) or die "$!";
    }
    return 1;
}