This post will describe the exercises and solutions for week three of Kirk Byers Python for Network Engineers.

Exercise two of week three we already completed in a previous post where we used a For loop to loop through the BGP output.

Let’s move on to exercise three instead:

In this exercise, Kirk is using pprint to print text so the first thing we need to do is to import this module:

Currently we have a massive string of information. Let’s print this string to see what it looks like:

That’s one giant string! We want to break up this giant string into a list of strings based on “\n”. As you saw above there each line has a “\n” before the next one starts. Let’s print the output of the list and the class type to show it’s a list.

If we run the script this is what we have so far:

So currently we have a list of information about the interface name, IP etc.

The next step is to create an empty list that we will append information to after we extract it from this current list:

What we want to do now is to loop through our list and get some information out of it. We use a For loop to loop through the list:

We don’t want any data from the line that has “Interface”, “IP-Address” in it, the header line. We use an if statement to match this and “continue” the loop if we find this string. When using “continue” we can hand the control back to the loop not doing anything in that iteration.

To get information from each line we will split the lines based on white space.

To not include lines that don’t have the correct number of fields we will do a check to see if the number of fields is 6.

Assuming that our list is the correct length, we want to map the information in the list into variables. Note that two variables are called “discard1” and “discard2” because we are not interested in keeping this information:

We only want to keep the lines where the line status is up and the line protocol is up. We use an if statement with “and” to make sure both are set to “up”.

After this check we want to append this information to the list we created before “show_ip_list”.

Then all that is left is to do some printing, using the pretty print module we imported before.

If we run this script this is the result:

Code available at Github. See you next time!

Python – Kirk Byers Course Week 3 Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: