標籤:
指令碼採用json設定檔,可以自訂,備份目錄,全量備份周期,增量備份時間等。
JSON設定檔:
{ "backupDir": "/data_backup", "archiveDir": "/archive_dir", "original": "/www/", "fullDayBase": 10}
主程式
#!/usr/bin/perluse 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;}
perl 增量、全量備份指令碼