QuestionQ97

VerifiedDevice-Level Network Automation

An engineer needs to enforce hostname compliance on a Cisco IOS XE router with Python and NETCONF. The engineer must retrieve the current hostname through NETCONF and, when it does not match, send the desired hostname to the running datastore. Construct the artifact using the code snippets. Not every option is used. Options can be used more than once.

Drag & Drop
from ncclient import 

device = {
    "host": "192.0.2.10",
    "port": 830,
    "username": "netops",
    "password": "C1sco12345",
    "hostkey_verify": False
}

with .(**device) as m:
    hostname_filter = """
    <filter xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" type="subtree">
        <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
            <hostname/>
        </native>
    </filter>
    """

    current = m.(source="running", filter=hostname_filter)
    desired = "BR-EDGE"
    if desired not in current.data_xml:
        payload = f"""
        <config>
            <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
                <hostname>{desired}</hostname>
            </native>
        </config>
        """

        m.(target="running", config=payload)
        print("Hostname updated.")
    else:
        print("Hostname already compliant.")
Explanation

The ncclient API exposes NETCONF sessions through manager.connect. get_config reads configuration from a specified datastore, so it retrieves the filtered hostname from running. Updating the hostname requires the NETCONF edit-config operation, with running as its target and the native IOS XE hostname configuration as the payload.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!