Monday, April 10, 2017

Backup and Restore WFA with Perl

My colleague (Warren Barnes) wrote this Perl script.  Apparently it is now possible to restore with rest as well.  (maybe it always was, but I couldn't figure it out).  So if I can find the time, I'll adapt my PowerShell version as well to restore with rest.







use strict;
use warnings;

use HTTP::Request::Common;
use LWP::UserAgent;
use Getopt::Long;
use WFAUtil;

use constant URI => 'https://%s/rest/backups?full=true';

$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;

my ( $target, $backup_file, $backup_dir );

GetOptions(
      'WFA=s'           => \$target,
      'BackupDir=s'     => \$backup_dir
) or die "Illegal command parameters";

my $wfa_util = WFAUtil->new();

# set up the user agent and ignore SSL certifcate issues
my $ua = LWP::UserAgent->new();
$ua->cookie_jar( {} );
$ua->credentials( 
      $target . ':443', 
      'wfa-ws-login', 
      $wfa_util->getCredentials( $target ) );
$ua->ssl_opts( 
      verify_hostname => 0, 
      SSL_verify_mode => 0 );

# Get the list of backup files with their timestamps
opendir DIR, $backup_dir or die $!;
my %backups =  map { get_timestamp( $_ ) => $_ } grep { /WFA.*zip/ } readdir DIR;
close DIR;

# What is the latest?
my ( $latest ) = sort { $b <=> $a } keys %backups;
$backup_file = join( '\\', $backup_dir, $backups{$latest} );
my $message = "Restored backup '$backup_file' to '$target'.";

# swap out the slashes otherwise the upload will not work
$backup_file =~ s/\\/\//g;
my $response = $ua->post(     
      sprintf( URI, $target ),
      Content_Type => 'form-data',
      Content => [ backupFile => [ $backup_file ] ] );

die $response->status_line . "\n"
      unless $response->is_success;
      
$wfa_util->sendLog( 'INFO', $message);

sub get_timestamp
{     
      ( $_[0] =~ /^WFA_Backup_(\d+).zip$/ )[0];
}

No comments :

Post a Comment