Last active
August 29, 2015 14:18
-
-
Save y0j/f0c28d9ff7f3cbfb2b68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use Net::SMTP; | |
# Change this to wherever you want to your backups to go | |
my $server = "d6x64.bb"; | |
my $storage = '/home/d6x64.bb'; | |
my $rsync_command = "/usr/bin/rsync -a --numeric-ids --delete --password-file=/root/rsync.p"; | |
my $target = 'rsync@8.8.8.8::full'; | |
my $log = '/var/log/backup/az.log'; | |
my $tail_ok = '/usr/bin/tail -n1 /var/log/backup/bb.log 2>&1'; | |
my $tail_error = '/usr/bin/tail -n2 /var/log/backup/bb.log 2>&1'; | |
# Report variables | |
our $email = 'admin@mail.com'; | |
our $subject = "Backup on $server has been finished"; | |
our @report; | |
our $start_date = (localtime(time)); | |
our $end_date; | |
# And whatever you wnat to exclude, if anything | |
my @rsync_exclude = | |
qw( | |
'/proc/' | |
'/var/run/' | |
'/tmp/' | |
'/var/tmp/' | |
'/sys/' | |
); | |
# Functionality and time parts | |
my @days = qw(sunday monday tuesday wednesday thursday friday saturday); | |
my $dtoday = (localtime(time))[6]; | |
my $today = $days[$dtoday]; | |
my $yesterday = $days[ $dtoday == 0 ? 6 : $dtoday - 1 ]; | |
sub run($) { | |
my $command = shift; | |
system($command) == 0 or die $!; | |
} | |
# Remove todays directory, since it is now a week old | |
run "rm -rf $storage/$today" if -e "$storage/$today"; | |
# Then copy yesterday's directory to today, using hard links | |
run "cp -al $storage/$yesterday $storage/$today" if -e "$storage/$yesterday"; | |
# And finally update today's directory using rsync | |
foreach (@rsync_exclude) { | |
$rsync_command .= " --exclude=$_ \\\n"; | |
} | |
$rsync_command .= "--log-file=$log $target $storage/$today"; | |
# Exception if we catch errors | |
eval { | |
run $rsync_command; | |
}; | |
if ($@) { | |
@report = `$tail_error`; | |
$end_date = (localtime(time)); | |
send_report(); | |
exit; | |
} | |
# Parse log if all is ok and report | |
@report = `$tail_ok`; | |
$end_date = (localtime(time)); | |
send_report(); | |
# Create and send report | |
sub send_report { | |
my $smtp = Net::SMTP->new('localhost'); | |
$smtp->mail($ENV{USER}); | |
$smtp->to($email); | |
$smtp->data(); | |
$smtp->datasend("Subject: $subject\n"); | |
$smtp->datasend("Started at: $start_date\n"); | |
$smtp->datasend("Finished at: $end_date\n"); | |
$smtp->datasend("\n"); | |
$smtp->datasend("@report\n"); | |
$smtp->datasend("\n"); | |
$smtp->dataend(); | |
$smtp->quit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment