Categories
Fortigate

Fortigate backup script using SCP

At work, we have a whole bunch of fortigate firewalls, and we like to backup them.

I found several scripts to do that, but none of them worked in the way I wanted them to, so I made mine.

It backs up a list of fortinet, using a read only admin of the firewall that is only allowed to log in from the backup server IP, stores it in a date based directory, and zips yesterday’s folder so as to save space.
Afterwards, it sends an email containing the logs to a specified email address.

Here it is:


#!/usr/bin/perl
use Net::OpenSSH;
use strict;
use Time::Piece;
use Time::Seconds;
use Archive::Zip qw( :ERROR_CODES );
use Archive::Zip::Tree;
use File::Path qw(make_path remove_tree);
use Mail::Mailer;

my $user = "BACKUP_USER";
my $password = "Password";
my $ip;
my @firewallips;
my $ssh;
my $date;
my $backuplocation;
my $backupdir;
$backuplocation = "/backup/location/";
my $from_address = "sender\@domain.com";
my $to_address = "recipient_address\@domain.com";
my $server = "mail.server.com";
my $subject = "Fortigate Backup Log";
my $body;
my $mailer = Mail::Mailer->new('smtp', Server => $server);

$date = `date +%Y%m%d`;
chomp($date);
$backupdir = $backuplocation.$date;
mkdir ($backupdir);

@firewallips =
(
'firewall hostname',
'or IP',

);

foreach $ip (@firewallips)
{
$ssh = Net::OpenSSH->new($ip, user => $user, password => $password);
$ssh->scp_get("sys_config", $backupdir."/".$ip."\.cfg") or $body .= $ip.": scp failed: " . $ssh->error."\n";
}

my $now = localtime();
my $yesterday = $now - ONE_HOUR*($now->hour + 12);
$yesterday = $yesterday->strftime('%Y%m%d');
my $yesterdaydir = $backuplocation.$yesterday;
my $zip = Archive::Zip->new();

if ($zip->addTree($yesterdaydir, $yesterday) != AZ_OK) {
$body .=  "Error adding file to zip!\n";
} else {
$body .=  "Successfully added file to zip!\n";
}
if ($zip->writeToFileNamed($backuplocation.'/'.$yesterday.'.zip') != AZ_OK) {  # write to disk
$body .=  "Error in archive creation!";
} else {
$body .=  "Archive created successfully!";
remove_tree($yesterdaydir);
}

$mailer->open({
From    => $from_address,
To      => $to_address,
Subject => $subject,
});
print $mailer $body;
$mailer->close();

Leave a Reply

Your email address will not be published. Required fields are marked *