Skip to content

Instantly share code, notes, and snippets.

@rz3n
Last active August 24, 2021 20:08
Show Gist options
  • Save rz3n/88680c7faa0a23400e5e204d4d814d40 to your computer and use it in GitHub Desktop.
Save rz3n/88680c7faa0a23400e5e204d4d814d40 to your computer and use it in GitHub Desktop.
Remote backup for Fortigate using SSH
#!/usr/bin/python3
from datetime import datetime
import gzip
import os
import subprocess
from subprocess import STDOUT, check_output
import yaml
config_file = "config.yml"
success = 0
error = 0
with open(config_file, 'r') as config:
try:
conf = yaml.safe_load(config)
except yaml.YAMLError as exc:
print(exc)
# parameters
compression = conf["compression"]
destination = conf["destination"]
# now
def now():
now = datetime.now()
date = now.strftime("%Y-%m-%d")
return date
# compress
def compress(file):
fp = open(file, "rb")
data = fp.read()
bindata = bytearray(data)
with gzip.open(file+'.gz', "wb") as f:
f.write(bindata)
os.remove(file)
# copy_backup
def copy_backup(name, user, host, port, key_file, destination):
command = 'scp -P ' + str(port) + ' -i ' + key_file + ' ' + user + '@' + host + ':sys_config ' + destination + ' || true'
p = subprocess.run([command], shell=True)
return p
# main
if __name__ == '__main__':
for i in range(len(conf["fortigates"])):
name = conf["fortigates"][i]["name"]
desc = conf["fortigates"][i]["desc"]
user = conf["fortigates"][i]["user"]
host = conf["fortigates"][i]["host"]
key_file = conf["fortigates"][i]["key_file"]
port = conf["fortigates"][i]["port"]
filename = destination + name + '_' + now() + '.conf'
print('>> backup from ' + desc)
action = copy_backup(name, user, host, port, key_file, filename)
if action.returncode == 0:
if compression:
print(' compressing...')
compress(filename)
success += 1
if action.returncode == 1:
error += 1
print('')
print('')
print('Summary:')
print(' Hosts total: ' + str(len(conf["fortigates"])))
print(' Success: ' + str(success))
print(' Error: ' + str(error))
---
destination: files/
compression: true
fortigates:
- name: FG_001
desc: Client 01
key_file: '~/.ssh/somekey'
user: admin
host: xx.xx.xx.xx
port: 22
- name: FG_002
desc: Client 02
key_file: '~/.ssh/somekey'
user: admin
host: xx.xx.xx.xx
port: 22
Simple python script for remotely backup Fortigates using SSH.
The public key must be previously configured in your fortigate.
```
config system admin
edit admin
set ssh-public-key1 "ssh-rsa your-key"
end
end
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment