python3用于备份Fortigate防火墙

作为运维工程师,需要定期去备份网络设备的配置文件,以备不时之需。有问题随时交流

1、打开Fortigate web管理,当然使用命令也是可以的,系统管理——访问配置-新建 名称为 fg-api

2、注意权限,设置为 读/写 ,点确认

3、新建管理员,系统管理-管理员-新建- REST API Admin , 信任的主机就是执行python脚本的主机ip,复制新API key (对应表格里面的access_token)

新建Fortigate设备列表文件,文件名为fortigate_devices.csv 包含两个字段ip,access_token 例如以下格式

ip,access_token
192.168.20.1,xs0jnxjHpsrskh8bHrNs3sz7gnwppb
192.168.21.1,58kxgwHccg9jgbhfyhg8kjH7H7f448

以下python脚本,可以尝试一下

#!/usr/bin/env python3
# coding=utf-8
import os
import csv
import requests
from datetime import datetime

# CSV 文件路径
csv_file_path = r'C:\Users\Administrator\PycharmProjects\my\backup\Fortigate\fortigate_devices.csv'

# API URL 基础部分注意修改成自己的设备端口
base_api_url = 'https://{ip}:10443/api/v2/monitor/system/config/backup?scope=global&access_token={access_token}'

# 禁用https安全请求警告
requests.packages.urllib3.disable_warnings()


def backup_device(ip, access_token, date_folder):
    try:
        # 构造完整的 API URL
        api_url = base_api_url.format(ip=ip, access_token=access_token)

        # 通过API路径获取配置文件
        response = requests.get(api_url, verify=False)
        response.raise_for_status()  # 如果响应状态不是200,将抛出HTTPError异常

        # 文件备份路径
        backups_path = 'backup/Fortigate'
        os.makedirs(backups_path, exist_ok=True)  # 创建备份目录,如果已存在则跳过

        # 创建日期文件夹
        date_folder_path = os.path.join(backups_path, date_folder)
        os.makedirs(date_folder_path, exist_ok=True)

        # 切换到日期文件夹
        current_dir = os.getcwd()
        os.chdir(date_folder_path)

        filename = ip + '.conf'

        # 把配置文件数据写入到文件
        with open(filename, 'wb') as f:
            f.write(response.content)

        # 切换回原来的目录
        os.chdir(current_dir)

        print(f'备份完成!设备IP: {ip}')

    except requests.exceptions.HTTPError as errh:
        print(f"HTTP Error: {errh}, 设备IP: {ip}")
    except requests.exceptions.ConnectionError as errc:
        print(f"Error Connecting: {errc}, 设备IP: {ip}")
    except requests.exceptions.Timeout as errt:
        print(f"Timeout Error: {errt}, 设备IP: {ip}")
    except requests.exceptions.RequestException as err:
        print(f"OOps: Something Else {err}, 设备IP: {ip}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}, 设备IP: {ip}")


# 获取当前日期
current_date = datetime.now().strftime('%Y_%m_%d')

# 读取 CSV 文件
with open(csv_file_path, mode='r', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    for row in reader:
        ip = row['ip']
        access_token = row['access_token']
        backup_device(ip, access_token, current_date)
posted @ 2024-11-13 11:16  凡人的四季  阅读(3)  评论(0编辑  收藏  举报