Python3 Network Programming – Using loops to script VLAN configuration, explanation of Python terminology, and lab demo to see it work!

PyLoopsTop

I have created a new Topology consisting of just a switch to demonstrate using “Loops” and “Concatenation” to demonstrate how to create a ton of VLANs, using the Loop to define the “Iterations” or number of times the function is run, and using Concatenation to allow “Integers” and “Strings” in Python to play well together.

Given all this I threw together a quick freestyle in IDLE to demonstrate “Concatenation” and “Literals” to review quick before getting into the Automation portion.

A quick review of some basic Python concepts demonstrated in IDLE

Below is a demonstration of “Operators” and “Literals” in this demo:

ConcatExample

Literals are things like numeric integers (numbers), Operators are things like +, =, with many many more than is described in great detail here, which details all operators in detail such as Floats (Integers with decimals) / Multiplication / a lot – Go check it out.

Above we see that str(#) can be used to take an Integer and set it to function as a String Literal, for example when I do str(a) + str(b) it produces ’12’ instead of 12, making it a String literal rather than an Integer literal.

Its also shown I can put str(c) + d = ‘3Hello World!’ and the other way around, so this is something to pay close attention to on DEVASC exam day if examining output, if an Integer is with ‘#’ or “#” in the output it is a String Literal rather than an Integer Literal.

So we can make Integers into Strings, why does this matter?

Good question!

This matters in this demo because we will use Concatenation to create 50 VLANs on our Switch in the Topology, which will add the String Literal “VLAN” to each “Iteration” of a Range we enter into a “For” loop we create to automate creating VLANs.

To demonstrate this concept I will bring up the Visual Studio Code script that I grabbed from the Telnet template I have been using for all automation shown below:

VLAN_Loop1

A quick review of some details for the two loops “if” and “for” shown above

  • You will always end the beginning line of the loop with a colon :
  • You will need to keep certain level functions at a proper 4 space indentation
  • When doing a Telnet Write or tn.write, the str(x) will need to include .encode(‘ascii’) to instruct Python to write the text in a format Cisco IOS understands via Telnet
  • b”\n” is “Line Feed” in Python scripting, so it basically instructs the script to move down a line before executing the next line, this is why its not generally used in writing scripts executed within Python but IS used for Telnet Automation

Line 12-14 shown here is simply executing the Username / Password input when first executing the script, which is why the enable and enable secret is written immediately after, follow by conf t for global config to start writing things to running memory.

Now a quick review of the VLAN creation loop / concatenation for this demo:

Starting the loop:

Line 20  = for n in range (2,50) means for each integer in the defined range, execute the code with, as indicated by the indentation – In Python n defines ‘Integer’ in the script.

Using Concatenation to use both String Literals and Integers from the Loop:

Line 21 = “VLAN ” + str(n).encode(‘ascii’) means it will write “VLAN 2″ defining the string literal to be written in ASCII that the IOS device will understand, and the + b”\n” is basically a line break or escape telling Python to move onto the next line in the script.

Line 22 = The VLAN # will now be created, and this line will give each VLAN the name of “Auto_VLAN_#” again in ASCII that the CLI will understand, also ending with the line break or escape of b”\n” to indicate that Iteration is complete and move onto the next

Note in line 21 a space in the “VLAN ” or the Concatenation does stick the String # directly to the “VLAN” output, whereas in Line 22 I do not use a space for the VLAN name as it would not recognize the space so it tags the # right onto the end of the name!

Once it completes Iterations 2-50 the script will stop executing, and jump to the next lines which is end / wr / exit / print so we can see the output of the CLI in your NetworkAutomation Host!

So in my previous automation lab, had I put for loop somewhere in the script for SW1 and SW2 they would have VLANs 1-50 with a name “Auto_VLAN_#” matching the VLAN # that was created via this script – In this demo I will only be doing the VLAN creation.

I know that is a lot of Python talk, so now lets see it in action!

This is the entire script I will be sending to the switch, the switch as been pre-configured with a management IP on VLAN 1 and username / password / secret to log in so that this NetAuto host can connect to it via Telnet – Remember Automation via Telnet is not “Zero Touch Provisioning” like you can do with Viptela and vEdge devices!

Anyhow, here is the code in raw text format from Visual Studio Code:

import getpass
import telnetlib
HOST = “192.168.238.150”
user = input(“Enter your remote account: “)
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b”Username: “)
tn.write(user.encode(‘ascii’) + b”\n”)
if password:
    tn.read_until(b”Password: “)
    tn.write(password.encode(‘ascii’) + b”\n”)
tn.write(b”enable\n”)
tn.write(b”loopedback\n”)
tn.write(b”conf t\n”)
for n in range (2,10):
    tn.write(b”vlan ” + str(n).encode(‘ascii’) + b”\n”)
    tn.write(b”name Auto_VLAN_” + str(n).encode(‘ascii’) + b”\n”)
tn.write(b”end\n”)
tn.write(b”wr\n”)
tn.write(b”exit\n”)
print(tn.read_all().decode(‘ascii’))
Some things to note with the above script
  • .encode(‘ascii’) is used for any tn.write string that may contain integers, but when just doing a tn.write it is not used, as it will send plain text strings / commands
  • Including \n in strings is equivalent to hitting enter in the CLI
  • The enable secret being plain text should not be used outside of a lab environment (especially using telnet!)
  • All info that comes back to the host is printed with .decode(‘ascii’) as well

Again I use Visual Studio Code as it really helps with learning Python, as it marks errors and suggests fixes if any, and will also show you what certain pieces of the code are if you hover over the character. Cannot recommend it enough!

With that, lets add VLANs 2-10 using Python to SW1!

A quick verification before running the script:

VLAN_Loop2

Running code on NetworkAutomation Host:

VLAN_Loop3

Success! I forget that the “range” will stop 1 iteration short of the # as once it hits that final iteration it ends to loop and moves on down the script, so we created VLANs 2-9 however lets verify on the switch as well:

VLAN_Loop4

And if we want to add say an additional 10 VLANs we can just change the range value in the script from range(10,21) as I will do now and run the script:

VLAN_Loop5

Its just that simple, and this is really loops at their most basic for network automation, as lets face it who wants 50 vlans all named “Automated_Vlan_#” on their switches?

And this is Network Automation Configuration at its very most basic.

Imagine standardizing and securing all Cisco network devices with a script!

Network Engineers of today just need to know and love this!

Think of these two scenarios where this skillset puts you ahead of the pack:

1. You are a freelance consultant, and can walk into a customer site and run a few scripts to turn on all the bells and whistles needed for QoS / Segmenting Network Traffic / Etc

2. You work for a Managed Service Provider with hundreds of customers being on-boarded every year, but you are inheriting a complete mess of a network, but its no sweat for you because you can run a few scripts and all their devices are standardized to your companies specifications!

Whether to a hiring manager or a potential client for your company, this skillset sells itself, there are very few cases standardization across all switches is not ideal!

The more I learn the more I see the value in this skillset, so I hope more people get interactive in the DevNet communities and Study Groups like I am participating in starting July 14th, as the community could use some more great automation engineers that actively participate in growing the community!

And that is my rant on needs to know Automation, see you all on the next one 🙂

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s