Back up a device over NETCONF
NETCONF asks the device for its configuration as structured XML instead of reading it off a screen. There are no prompts, pagers or banners to deal with, and the answer is the same shape every time. Junos, IOS-XE, IOS XR, NX-OS and many optical and service provider platforms support it. This recipe fetches the running config with the Python library ncclient and stores it as one path = value line per setting.
When to use it
- The device supports NETCONF, and you want a backup that doesn’t depend on CLI output formatting.
- You want to check settings with policies by their full path, such as
system.ntp.server[name=192.0.2.123].
Keep the normal CLI backup alongside it if your team reads configs in CLI form. Use a second device record for the NETCONF backup, as the snapshot recipe explains.
What you need
- NETCONF enabled on the device, normally on TCP port 830 (
set system services netconf sshon Junos,netconf-yangon IOS-XE). - ncclient installed in the scripts’ Python environment:
sudo /opt/rconfig-sie/venv/bin/pip install ncclient. See get your server ready for scripts. - The device’s NETCONF host key recorded in a file the script reads. ncclient checks host keys against
~/.ssh/known_hosts, so the script points its home folder at thekeysfolder. Record each device once, as the web user:
KEYS=/var/www/html/rconfig8/current/storage/app/rconfig/scripts/keyssudo -u apache mkdir -p $KEYS/netconf-home/.ssh # www-data on Ubuntusudo -u apache sh -c "ssh-keyscan -p 830 192.0.2.10 >> $KEYS/netconf-home/.ssh/known_hosts"Check the key you recorded against the device’s own fingerprint before trusting it.
The template
main: name: "SIE - NETCONF backup" desc: "Collects the running config over NETCONF and stores it flattened"
connect: timeout: 180 idletimeout: 120 # a large config can take a while to arrive 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: netconf"The command
The first argument is ncclient’s device handler: junos, iosxe, iosxr, nexus, or default for anything else.
/opt/rconfig-sie/venv/bin/python {script_path}netconf-get-config.py junos {device_ip} {device_username} {device_password}The script
Save it as netconf-get-config.py in the scripts folder.
#!/usr/bin/env python3"""Collect the running config over NETCONF and store it as one line persetting, for the rConfig Script Integration Engine.
Usage: netconf-get-config.py <handler> <host> <username> <password>
Flattened config to stdout. Progress, errors and the success marker to stderr.Exit code 0 on success, 1 on any failure."""
import osimport sysimport xml.etree.ElementTree as ET
KEYS = "/var/www/html/rconfig8/current/storage/app/rconfig/scripts/keys"os.environ["HOME"] = f"{KEYS}/netconf-home" # ncclient reads ~/.ssh/known_hosts
from ncclient import manager # noqa: E402 (after HOME is set)
PORT = 830# Elements whose values change without a config change. Extend for your platform.VOLATILE = {"last-changed", "last-modified", "configuration-changed"}
def note(message): print(message, file=sys.stderr)
def fail(message): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1)
def local(tag): """Drop the XML namespace: '{urn:...}interface' -> 'interface'.""" return tag.rsplit("}", 1)[-1]
def flatten(element, path, out): """One 'path = value' line per leaf. List entries are keyed by their name child where they have one, so adding an entry doesn't renumber the rest.""" children = list(element) if not children: text = (element.text or "").strip() if local(element.tag) not in VOLATILE: out.append(f"{path} = {text}" if text else path) return seen = {} for child in children: tag = local(child.tag) if tag in VOLATILE: continue name = next((c.text.strip() for c in child if local(c.tag) == "name" and c.text), None) if name is not None: key = f"{tag}[name={name}]" else: seen[tag] = seen.get(tag, 0) + 1 key = tag if seen[tag] == 1 else f"{tag}[{seen[tag]}]" flatten(child, f"{path}.{key}" if path else key, out)
def main(): if len(sys.argv) < 5: fail("usage: netconf-get-config.py <handler> <host> <username> <password>") handler, host, username, password = sys.argv[1:5]
note(f"connecting to {host}:{PORT} over NETCONF ({handler})") try: with manager.connect( host=host, port=PORT, username=username, password=password, device_params={"name": handler}, hostkey_verify=True, allow_agent=False, look_for_keys=False, timeout=90, ) as session: reply = session.get_config(source="running") xml = reply.data_xml except Exception as exc: # ncclient raises several transport and RPC errors fail(f"{type(exc).__name__}: {exc}")
try: root = ET.fromstring(xml.encode("utf-8") if isinstance(xml, str) else xml) except ET.ParseError as exc: fail(f"the reply was not valid XML: {exc}")
lines = [] for top in root: # skip the <data> wrapper flatten(top, local(top.tag), lines) if not lines: fail("the running config came back empty, refusing to store it")
sys.stdout.write("\n".join(lines) + "\n") note(f"SIE-OK: netconf {len(lines)} settings from {host}") return 0
if __name__ == "__main__": sys.exit(main())What gets stored
For part of a Junos configuration:
configuration.system.host-name = edge-rtr-01configuration.system.ntp.server[name=192.0.2.123]configuration.system.ntp.server[name=198.51.100.123]configuration.interfaces.interface[name=ge-0/0/0].description = uplink-to-coreconfiguration.interfaces.interface[name=ge-0/0/0].unit[name=0].family.inet.address[name=192.0.2.1/30]Each line names the full path to the setting, so a change reads as “this setting on this interface”, and a policy can check one line without worrying about where it sits in the file.
Adapting it
- Only part of the config. Pass a subtree filter to
get_config(filter=("subtree", "<configuration><system/></configuration>")) to collect one section. - Keep the XML. If your team prefers XML, print
xmlinstead of the flattened lines. rConfig trims the indentation, so the stored XML is valid but flat. - Keys instead of a password. Pass
key_filenamewith a key in thekeysfolder, and drop{device_password}from the command. - List entries keyed by something other than
name. Some models key lists byidorindex. Add those to the lookup inflatten.