cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
734
Views
5
Helpful
2
Replies

How to iterate to the ipv4 address NETCONF XML - Devnet course

_|brt.drml|_
Level 1
Level 1

Hi there

I'm trying to create a script after relentless hours of study :-)

I just need to know how to iterate through the xml data and 'print' out the requested IPV4 address

 

This is the script:

[all information is more then welcome: the 'output print to a txt' file is here not finished.] just got stuck in the basics

#!/usr/bin/env python
# the imports are modules that need to be installed on your system! If not the script will fail!
import json
import os
import sys
import time
import threading
from ncclient import manager
import xmltodict
import xml.dom.minidom
from pprint import pprint


# Get the absolute path for the directory where this file is located "here"
here = os.path.abspath(os.path.dirname(__file__))

# Get the absolute path for the project / repository root
project_root = os.path.abspath(os.path.join(here, "../.."))

# Extend the system path to include the 'connecting device' in the root and import the env files -> the username pwd etc.
sys.path.insert(0, project_root)
import env_lab

# Create an XML filter for targeted NETCONF queries -> XML filters the requested output -> this is the data model that is needed to talk to the IOS Xe
netconf_filter = """
<filter>
  <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
    <interface></interface>
  </interfaces>
</filter>"""

print("Opening NETCONF Connection to {}".format(env_lab.EoIP["host"]))

# Open a connection to the network device using ncclient
with manager.connect(
        host=env_lab.EoIP["host"],
        port=env_lab.EoIP["netconf_port"],
        username=env_lab.EoIP["username"],
        password=env_lab.EoIP["password"],
        hostkey_verify=False
        ) as m:

    print("Sending a <get-config> operation to the device.\n")
    # Make a NETCONF <get-config> query using the filter
    netconf_reply = m.get_config(source = 'running'filter = netconf_filter)

print("Here is the raw XML data returned from the device.\n")
# Print out the raw XML that returned
print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml())
print("")

# Parse the returned XML to an Ordered Dictionary -> to get the data out of it.
netconf_data = xmltodict.parse(netconf_reply.xml)
interfaces = netconf_data["rpc-reply"]["data"]["interfaces"]["interface"]
print(interfaces)
print("")

# Create a list of interfaces
for interface in interfaces:
    print("Interface : {name} : ip : {ip} : netmask : {mask} : Status : {status} : ".format(
            name = interface["name"],
            ip = interface["ipv4"]["address"]["ip"],
            mask = interface["ipv4"]["address"]["netmask"],
            status  = interface["enabled"]
            )
        )
print("\n")

host=env_lab.EoIP["host"]
username=env_lab.EoIP["username"]
#sleep for a while - so windows can follow !
time.sleep(1)

print("generating the outputfile of {}".format(host))
time.sleep(0.75)
print("The file is created by user: {}".format(username))
time.sleep(0.75)
print("The file is generated at location: {}".format(here))
time.sleep(0.75)
# Parse the entire folder to make ready for printing out
output_xml = xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml()

with open("{}.txt".format(host), "w"as file:
    file.write(output_xml)





1 Accepted Solution

Accepted Solutions

omz
VIP Alumni
VIP Alumni

Hi 

Whats the issue? Is it the key error?

Interface : GigabitEthernet1 : ip : 10.10.20.48 : netmask : 255.255.255.0 : Status : true :
Interface : GigabitEthernet2 : ip : 10.255.255.1 : netmask : 255.255.255.0 : Status : true :
Traceback (most recent call last):
  File "test.py", line 57, in <module>
    ip = interface["ipv4"]["address"]["ip"],
KeyError: 'address'

 If the issue is the key error - its because the interface doesn't have an address configured.

You can use a try-except block to catch the key error.

Something like this may work - 

# Create a list of interfaces
for interface in interfaces:
    try:
        print("Interface : {name} : ip : {ip} : netmask : {mask} : Status : {status} : ".format(
            name = interface["name"],
            ip = interface["ipv4"]["address"]["ip"],
            mask = interface["ipv4"]["address"]["netmask"],
            status  = interface["enabled"]
            )
        )
    except KeyError:
        print("Interface : {name} : Status : {status} : ".format(
            name = interface["name"],
            status  = interface["enabled"]
            )
        )

View solution in original post

2 Replies 2

omz
VIP Alumni
VIP Alumni

Hi 

Whats the issue? Is it the key error?

Interface : GigabitEthernet1 : ip : 10.10.20.48 : netmask : 255.255.255.0 : Status : true :
Interface : GigabitEthernet2 : ip : 10.255.255.1 : netmask : 255.255.255.0 : Status : true :
Traceback (most recent call last):
  File "test.py", line 57, in <module>
    ip = interface["ipv4"]["address"]["ip"],
KeyError: 'address'

 If the issue is the key error - its because the interface doesn't have an address configured.

You can use a try-except block to catch the key error.

Something like this may work - 

# Create a list of interfaces
for interface in interfaces:
    try:
        print("Interface : {name} : ip : {ip} : netmask : {mask} : Status : {status} : ".format(
            name = interface["name"],
            ip = interface["ipv4"]["address"]["ip"],
            mask = interface["ipv4"]["address"]["netmask"],
            status  = interface["enabled"]
            )
        )
    except KeyError:
        print("Interface : {name} : Status : {status} : ".format(
            name = interface["name"],
            status  = interface["enabled"]
            )
        )

Okay, this was the solution.

I guess this is the same issue with processing via ElementTree. With that I could generate the entire 'xml' block as a list. But I could not get results with the find or findall ...

I would have hoped that an "empty" value would be 'visible'.



Well I certainly learned something.



Thank you for this response. I hope it would help for others to come!