Description
This article is designed to automate the backup process of a FortiGate device's configuration to a TFTP server. It utilizes SSH to connect to the FortiGate and execute the backup command periodically at a specified interval.
The script also includes error handling and logging to ensure that the backup process is reliable and can be monitored.
Scope
FortiGate.
Solution
To use this script, customize the variables at the beginning of the script to match the environment. CentOS will be used for this scenario.
#!/bin/bash
# Define variables
hostname="<management_ip_address>"
username="<username>"
interval=<interval_in_seconds> # e.g., 86400 for 24 hours or 604800 for a week
tftp_ip="<TFTP_IP_address>"
log_file="/var/log/backup_script.log" # Change the log file location to your desired path
# If ssh key is required, please use this line
# private_key="/path/to/private/key"
# Function to log messages
log() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" >> "$log_file"
}
# Check if sshpass is installed
if ! command -v sshpass &> /dev/null; then
echo "sshpass is not installed. Installing..."
sudo yum install -y sshpass
fi
# Main loop
while true; do
log "Backup is starting..."
file=$(date +"%F-%H%M%S")
# Perform backup
if sshpass -p "$password" ssh -o StrictHostKeyChecking=no "$username@$hostname" "config global; execute backup full-config tftp backup-config-$file.conf $tftp_ip; exit"; then
log "Backup successful. File: backup-config-$file.conf"
else
log "Backup failed!"
fi
sleep "$interval"
done
If SSH key authentication is required, uncomment the private_key variable and set it to the path of your private key file.
Note:
Ensure that sshpass is installed on the system running the script. If it is not installed, the script will attempt to install it using the sudo yum install -y sshpass command.
After customizing the variables, save the script to a file (e.g., fgt_backup.sh) and make it executable using chmod +x fgt_backup.sh.
Run the script using ./fgt_backup.sh to start the backup process.
The script will log the start of each backup, perform the backup, and log the result (success or failure) to the specified log file. The script will then sleep for the specified interval before starting the next backup.
Results:
2024-05-01 08:00:00 - Backup is starting...
2024-05-01 08:00:10 - Backup failed!
2024-05-01 08:05:00 - Backup is starting...
2024-05-01 08:05:10 - Backup successful. File: backup-config-2024-05-01-080510.conf
2024-05-02 08:00:00 - Backup is starting...
2024-05-02 08:00:10 - Backup successful. File: backup-config-2024-05-02-080010.conf
The Fortinet Security Fabric brings together the concepts of convergence and consolidation to provide comprehensive cybersecurity protection for all users, devices, and applications and across all network edges.
Copyright 2024 Fortinet, Inc. All Rights Reserved.