scsd-configs/code/backupfortigate.py
2025-10-15 20:18:06 -04:00

52 lines
1.4 KiB
Python

# /// script
# requires-python = ">=3.12"
# dependencies = [ "pexpect", "typer"]
# ///
# uv run backupfortigate.py 192.168.1.241 jpoland 'JPscsdfg12!'
import pexpect
import sys
import tempfile
import typer
from contextlib import suppress
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:
p.sendline("show full-configuration")
else:
p.sendline("show")
p.expect(prompt)
return(p.before[5:])
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()