How to configure Vlans using loops easily

In python, we can use loops if we want to repeat a task specified number of times.

The below code will print number from 2 to 9. So, here we are introducing the range keyword & it is important to note that the colon is important after the input in parentheses.

The print (n) section needs to spaced appropriately & the recommended number on spaces is 4 as per python standards. The indentation needs to be consistent

for n in range (2,10):
    print (n)

The output once the above is complied will be like this.

Output:

root@NetworkAutomation-1:~# python3 python33.py
2
3
4
5
6
7
8
9

You can visit the page for detailed information on the styling guide of python.

Now, let us see how we can take advantage of loops in creating Vlan’s. By changing the single value in the for loop, We can create as many number of vlans we require easily.

import getpass
import telnetlib

# we are specifing the IP address of the Switch.
# the username & password are variables, this is facilitated by getpass library we imported above

HOST = "192.168.0.14"
user = input("Enter your telnet username: ")
password = getpass.getpass()

# instructs python to telnet to the HOST whose IP is specified above

tn = telnetlib.Telnet(HOST)

# Reads the username & Password that user has inputed & parses to the device
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")

# writes below commands to the device, exits & then prints the output back to the terminal

tn.write(b"enable\n")
tn.write(b"kapil\n")
tn.write(b"conf t\n")

# the for loop below will create vlans 2 to 20 on the switch. 
# I am writing vlan & converting the n value to a string
for n in range (2,21):
    tn.write(b"vlan " + str(n).encode('ascii')+b"\n")
    tn.write (b"name Python_vlan " + str(n).encode('ascii') +b"\n")
tn.write(b"end\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))

Emphasis here on this particular block of code.

for n in range (2,21):
    tn.write(b"vlan " + str(n).encode('ascii')+b"\n")
    tn.write (b"name Python_vlan " + str(n).encode('ascii') +b"\n")

Now lets extend this vlan script to use a file containing IP addresses, login to the switch & push this configuration of Vlans to multiple Switches.

So, below is the topology I am using. I added 5 more switches to the network & created a base configuration on them with below & the IP addresses in my case are ranging from 192.168.0.15 to 192.168.0.19. I have also confirmed the reachability to these IP addresses from the automation server.

conf t
interface vlan 1
ip address {IP Address}
no shutdown
exit
username kapil password kapil
enable password kapil
line vty 0 4
transport input all
login local
end
write mem

below is the snapshot of my topology.

I have created file named “myswitches” and inputted the ip address of the switches in the file. & now below the script that is configured.

We are back here on the script, where we configure the Vlans line by line and not using the loop. If we use loops to create Vlan, then we will need to write a nested loop about which we will talk in the next example.

import getpass
import telnetlib
HOST = "localhost"
user = input("Enter user name: ")
password = getpass.getpass()

f= open('myswitches')

for ip in f:
    ip = ip.strip()  # Remove any leading/trailing whitespace or newline characters
    print ("configuting the switch" + (ip))
    HOST= ip
    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"kapil\n")
    tn.write(b"conf t\n")
    tn.write(b"vlan 2\n")
    tn.write(b"name python_test_vlan2\n")
    tn.write(b"vlan 3\n")
    tn.write(b"name python_test_vlan3\n")
    tn.write(b"vlan 4\n")
    tn.write(b"name python_test_vlan4\n")
    tn.write(b"end\n")
    tn.write(b"exit\n")

    print(tn.read_all().decode('ascii'))

Now, the same Vlan’s can also be created using a loop. Which is called a Nested Loop. below is the sample code

So, this below script can now pull the IP address of the Switch from a file & configure as many as Vlans we want on the switches.

import getpass
import telnetlib
HOST = "localhost"
user = input("Enter user name: ")
password = getpass.getpass()

f= open('myswitches')

for ip in f:
    ip = ip.strip()  # Remove any leading/trailing whitespace or newline characters
    print ("configuting the switch" + (ip))
    HOST= ip
    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"kapil\n")
    tn.write(b"conf t\n")

    for n in range(2, 21):
        tn.write(b"vlan " + str(n).encode('ascii') + b"\n")
        tn.write(b"name python_test_vlan" + str(n).encode('ascii') + b"\n")
    tn.write(b"end\n")
    tn.write(b"exit\n")

    print(tn.read_all().decode('ascii'))

Slightly modifying the above script we can use the below script to Backup Network devices using Python :

import getpass
import telnetlib

user = input("Enter user name: ")
password = getpass.getpass()

f= open('myswitches')

for ip in f:
    ip = ip.strip()  # Remove any leading/trailing whitespace or newline characters
    print ("Getting Running configuration of the Switch" + (ip))
    HOST= ip
    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"kapil\n")
    tn.write(b"ter len 0\n")
    tn.write(b"show run\n")
    tn.write(b"exit\n")

    readoutput = tn.read_all()
    # opens the file switch + HOST as writable file.
    saveoutput = open("switch" + HOST, "w")
    saveoutput.write(readoutput.decode('ascii'))
    saveoutput.write("\n")
    saveoutput.close
error: Content is protected !!