Last active
June 13, 2023 02:34
-
-
Save viniciusgonmelo/29e03a7b3696163172b5ad93b98ada71 to your computer and use it in GitHub Desktop.
Backup local de hosts remotos com rsync em Perl.
This file contains hidden or 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/env perl | |
# Script: files_rhosts-bak.pl | |
# Descrição: Backup de hosts remotos localmente | |
# o arquivo de configuração 'rhosts' deve estar no mesmo diretório do script | |
# os hosts remotos podem ser configurados em /root/.ssh/config ou $HOME/.ssh/config | |
# Exemplo de 'rhosts': | |
# RHOST_1=rhost-1:/home/usuario | |
# RHOST_2=USUARIO:[email protected]:/home/usuario | |
# RHOST_3=rhost-3:/ | |
# Exemplo de uso: sudo files_rhosts-bak --dest=/backup/rhosts | |
use 5.010; | |
use strict; | |
use warnings; | |
use Getopt::Long qw(:config pass_through); | |
use File::Path qw(rmtree); | |
use FindBin qw($RealBin); | |
use Log::Log4perl qw(:easy); | |
use POSIX qw(strftime); | |
my $backup_dir; | |
GetOptions( 'dest=s' => \$backup_dir ) | |
or die "Você deve fornecer o diretório de backup usando a opção --dest\n"; | |
mkdir $backup_dir, 0777 | |
or $!{EEXIST} | |
or die "Não foi possível criar o diretório de backup '$backup_dir': $!\n"; | |
Log::Log4perl->easy_init( | |
{ file => '>>/opt/backup_rhosts/backup_rhosts.log', | |
layout => '[%d] [%p] %m%n', | |
} | |
); | |
my $logger = Log::Log4perl->get_logger(); | |
$logger->info("Iniciando backup em '$backup_dir'"); | |
my $date = strftime '%Y%m%d', localtime; | |
open my $fh, '<', "$RealBin/rhosts" | |
or die "Não foi possível abrir o arquivo 'rhosts': $!\n"; | |
my %rhosts = map { split /=|\s+/; } <$fh>; | |
close $fh; | |
for my $rhost ( keys %rhosts ) { | |
my ( $ssh_host, $path ) = split /:/, $rhosts{$rhost}, 2; | |
my $host_name = lc $rhost; | |
$host_name =~ tr/_/-/; | |
my $tmp_dir = "$backup_dir/$host_name"; | |
my $tgz = "$backup_dir/$date\_$host_name.tgz"; | |
system | |
"rsync -aAXz root\@$ssh_host:$path $tmp_dir >> /opt/backup_rhosts/backup_rhosts.log 2>&1"; | |
system | |
"tar -C $backup_dir -czf $tgz $host_name >> /opt/backup_rhosts/backup_rhosts.log 2>&1"; | |
rmtree($tmp_dir); | |
} | |
$logger->info("Backup concluído em '$backup_dir'"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment