# /// script # requires-python = ">=3.12" # dependencies = [ "pexpect", "typer"] # /// # uv run backupfortigate.py 192.168.1.241 USERNAME PASSWORD import pexpect import sys import tempfile import typer from enum import Enum CONFIG_SUFFIX="conf" class ConfigType(Enum): FULL = 1 SHORT = 2 def download_fortigate_config(ip:str,username:str,password:str,whichtype:ConfigType): p=pexpect.spawn(f'ssh {username}@{ip}',encoding='utf-8') #p.logfile = sys.stdout p.expect("assword:") p.sendline(password) p.expect("#") prompt=p.before.lstrip() if whichtype==ConfigType.FULL: show_command="show full-configuration" else: show_command="show" p.sendline(show_command) p.expect(prompt) return(p.before[len(show_command)+1:]) def backup(ip:str,username:str,password:str): with tempfile.TemporaryDirectory(delete=False) as dirname: config_text = download_fortigate_config(ip=ip,username=username,password=password,whichtype=ConfigType.FULL) fg_fn=f"{dirname}/fg-full.{CONFIG_SUFFIX}" with open(fg_fn,"w") as outfile: outfile.write(config_text) config_text = download_fortigate_config(ip=ip,username=username,password=password,whichtype=ConfigType.SHORT) fg_fn=f"{dirname}/fg-short.{CONFIG_SUFFIX}" with open(fg_fn,"w") as outfile: outfile.write(config_text) print(dirname) if __name__ == "__main__": typer.run(backup) sys.exit()