Write an SIE script with NETCONF and ncclient
ncclient is the standard Python library for NETCONF. It opens an SSH session to the device’s NETCONF port and returns structured XML: no prompts, pagers or screen output to parse. This page is the short version; the NETCONF backup recipe is the full one, with flattened output.
Good for
- Devices with NETCONF enabled: Junos, IOS-XE, IOS XR, NX-OS and many optical and service provider platforms.
- Backups that must not depend on CLI formatting.
Set it up
sudo /opt/rconfig-sie/venv/bin/pip install ncclientncclient checks host keys against ~/.ssh/known_hosts. The web user’s home folder usually isn’t usable, so the script sets its own home to a folder under keys. Record each device’s NETCONF key there once:
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"The command
The first argument is ncclient’s device handler: junos, iosxe, iosxr, nexus or default:
/opt/rconfig-sie/venv/bin/python {script_path}my-netconf.py junos {device_ip} {device_username} {device_password}A minimal script
This one stores the XML as returned. rConfig trims the indentation, so the stored XML is valid but flat; the full recipe flattens it into one line per setting instead.
#!/usr/bin/env python3"""Minimal SIE script with ncclient: running config as XML.
Usage: ncclient-skeleton.py <handler> <host> <username> <password>"""
import osimport sys
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
def fail(message): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1)
def main(): if len(sys.argv) < 5: fail("usage: ncclient-skeleton.py <handler> <host> <username> <password>") handler, host, username, password = sys.argv[1:5]
try: with manager.connect(host=host, port=830, username=username, password=password, device_params={"name": handler}, hostkey_verify=True, allow_agent=False, look_for_keys=False, timeout=90) as session: xml = session.get_config(source="running").data_xml except Exception as exc: fail(f"{type(exc).__name__}: {exc}")
if not xml or not xml.strip(): fail(f"empty reply from {host}")
sys.stdout.write(xml.rstrip("\n") + "\n") print(f"SIE-OK: netconf xml from {host}", file=sys.stderr) return 0
if __name__ == "__main__": sys.exit(main())Habits that matter with ncclient
- Set
HOMEbefore importing ncclient. It works out whereknown_hostsis when it loads it. allow_agent=False, look_for_keys=Falsefor password logins, so it doesn’t try stray keys first and use up login attempts.- The right device handler.
defaultworks for standard NETCONF, but vendor handlers deal with each platform’s quirks.