Skip to content

NETCONF Python Script - Interface Status Retrieval (IOS XE)

Overview

This script demonstrates how to use NETCONF with Python (ncclient) to connect to a Cisco IOS XE device and retrieve interface operational status using YANG subtree filtering.

Specifically, it retrieves:

  • Interface name
  • Interface oper-status

The script connects to the Catalyst 8000v DevNet Sandbox device using NETCONF over SSH (port 830).


Prerequisites

1. Network Access

  • Active connection to the Cisco DevNet Sandbox VPN
  • Reachable device IP: 10.10.20.48

2. Python Environment

Python 3.8+ recommended

Install required packages:

pip install ncclient lxml

3. Device Access Details

Parameter Value
Host 10.10.20.48
Port 830
Username developer
Password C1sco12345

Script Purpose

This script performs the following actions:

  1. Opens a NETCONF session to an IOS XE device
  2. Sends a <get> request with a YANG subtree filter
  3. Requests only:

  4. <name>

  5. <oper-status>
  6. Prints the raw XML response
  7. Parses and prints interface names with their operational status

Download Script

Click to download the script directly:

Download NETCONF_Interface_status_retrieval.py


Full Script

#!/usr/bin/env python

from lxml import etree
from ncclient import manager

# Request information
username = "developer"
password = "C1sco12345"
hostname = "10.10.20.48"
port = 830

# Make NETCONF connection
device = manager.connect(
    host=hostname, port=port,
    username=username, password=password,
    hostkey_verify=False, device_params={},
    allow_agent=False, look_for_keys=False
)

# Define XML Filter Request (ietf-interfaces: interfaces-state)
xml_filter = """
<interfaces-state xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
  <interface>
    <name/>
    <oper-status/>
  </interface>
</interfaces-state>
"""

# Request data from device with XML Filter
netconf_response = device.get(('subtree', xml_filter))

# Print the XML Response
print('XML Response:')
print('-' * 80)
print(etree.tostring(netconf_response.data_ele, pretty_print=True).decode('utf-8'))

# Define XML Namespace for Find
ns_find = {
  "if": "urn:ietf:params:xml:ns:yang:ietf-interfaces",
}

# Find all interface elements
interfaces = netconf_response.data.findall(".//if:interface", namespaces=ns_find)

# Print parsed results
print('-' * 80)
for intf in interfaces:
    name = intf.find("if:name", namespaces=ns_find)
    oper = intf.find("if:oper-status", namespaces=ns_find)

    name_text = name.text if name is not None else "N/A"
    oper_text = oper.text if oper is not None else "N/A"

    print(f"{name_text}: {oper_text}")

print("\n")

# Close NETCONF session
device.close_session()