Back up every context on a multi-context device
Some devices are several devices in one box. A Cisco ASA in multiple context mode has a system configuration and a separate configuration for each security context. A normal backup sees only the context it logs in to. This recipe logs in once, lists the contexts, switches into each one and stores them all, each under a heading, so a new or deleted context shows up as well as changes inside one.
When to use it
- A Cisco ASA (or Firepower running ASA code) in multiple context mode.
- Any platform where one login gives you several separate configurations and a command to move between them. The same loop works for FortiGate VDOMs; see adapting it.
What you need
- Netmiko in the scripts’ Python environment. See get your server ready for scripts.
- An account that logs in to the admin context and is allowed to use
changeto. Accounts defined inside a single context can’t see the others.
The template
main: name: "SIE - Every context" desc: "Collects the system config and every security context"
connect: timeout: 300 # one config per context adds up idletimeout: 120 idleTimeout: 120 protocol: script
# exit_codes is deliberately left out: any non-zero exit fails the run.failure_criteria: error_patterns: - "ERROR:" success_patterns: - "SIE-OK: contexts"The command
/opt/rconfig-sie/venv/bin/python {script_path}asa-contexts.py {device_ip} {device_username} {device_password} {device_enable_password}The script
Save it as asa-contexts.py in the scripts folder.
#!/usr/bin/env python3"""Collect the system config and every security context from a Cisco ASA inmultiple context mode, for the rConfig Script Integration Engine.
Usage: asa-contexts.py <ip> <username> <password> [enable_password]
All configs go to stdout, each under a '===== context =====' line. Progress,errors and the success marker go to stderr. Exit code 0 on success, 1 on anyfailure."""
import sys
from netmiko import ConnectHandlerfrom netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
PROMPT = r"[>#]\s*$"VOLATILE_PREFIXES = (": Saved", ": Written by", ": Serial Number", "Cryptochecksum:")
def note(message): print(message, file=sys.stderr)
def fail(message): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1)
def context_names(show_context): """Read context names from 'show context'. The current context is marked '*'.""" names = [] for line in show_context.splitlines(): line = line.strip() if not line or line.startswith(("Context Name", "Total")): continue names.append(line.lstrip("*").split()[0]) return names
def clean(text): return "\n".join( line for line in text.splitlines() if not line.strip().startswith(VOLATILE_PREFIXES) ).strip()
def main(): if len(sys.argv) < 4: fail("usage: asa-contexts.py <ip> <username> <password> [enable_password]") host, username, password = sys.argv[1:4] secret = sys.argv[4] if len(sys.argv) > 4 else ""
device = {"device_type": "cisco_asa", "host": host, "username": username, "password": password, "secret": secret, "conn_timeout": 20}
sections = [] try: with ConnectHandler(**device) as conn: if secret: conn.enable()
conn.send_command("changeto system", expect_string=PROMPT) conn.set_base_prompt() names = context_names(conn.send_command("show context")) if not names: fail("'show context' listed no contexts; is the ASA in multiple context mode?") note(f"found {len(names)} contexts: {', '.join(names)}")
sections.append(("system", conn.send_command("show running-config", read_timeout=120)))
for name in sorted(names): conn.send_command(f"changeto context {name}", expect_string=PROMPT) conn.set_base_prompt() note(f"collecting context {name}") sections.append((name, conn.send_command("show running-config", read_timeout=120)))
conn.send_command("changeto system", expect_string=PROMPT) except NetmikoAuthenticationException: fail(f"authentication failed for {username}@{host}") except NetmikoTimeoutException: fail(f"timed out talking to {host}") except Exception as exc: fail(f"{type(exc).__name__}: {exc}")
output = [] for name, config in sections: config = clean(config) if not config: fail(f"context {name} returned an empty config") output += [f"===== context {name} =====", config, ""]
sys.stdout.write("\n".join(output)) note(f"SIE-OK: contexts system plus {len(sections) - 1} from {host}") return 0
if __name__ == "__main__": sys.exit(main())Contexts are collected in name order, so the stored backup keeps the same order however the ASA lists them.
What gets stored
===== context system =====hostname fw-dc-01context adminallocate-interface Management0/0config-url disk0:/admin.cfg
===== context admin =====hostname admininterface Management0/0nameif managementip address 192.0.2.60 255.255.255.0
===== context tenant-a =====hostname tenant-aaccess-list outside_in extended permit tcp any host 203.0.113.10 eq httpsAdapting it
- FortiGate VDOMs. Use the
fortinetdriver and the same loop: get the list of VDOMs, then for each one sendconfig vdom,edit <name>, the command that shows its configuration, andend. The commands for listing VDOMs vary by FortiOS release, so check yours. - One file per context in rConfig. Make one command per context in the command group, each passing the context name as an extra argument, and collect a single context per run. Each context then has its own history in rConfig.
- Fewer secrets in the backup. ASA configs contain hashed passwords and keys. Mask them with the cleaning output helpers if the backups are widely viewed.