My first Python script

Efficiency is very important in every task. Efficient processes, procedures lead to time saving, which leads to either saving money or additional revenue. Automation in information technology has become an important skill and that is where Python seems to be shinning these days. Many network engineers are using Python to automate tasks and increase overall efficiency.

I do not have any programming background and not something I have indulged into in the past other than some small things with batch files, auto hot key, excel etc. Working on some recent projects made me realize that I need to become more efficient and learn some Python.

With that in mind I worked on my very first python script, it isn’t amazing but gets the job done and its my first step towards learning something new. Will be posting them here as a reference and to hopefully get some feedback and improve.

Script to log into Cisco WLC

I needed to do the following:

  • Log into a Cisco WLAN Controller
  • Execute commands and display in the terminal window
  • Execute commands and dump the output in the text file.

This code below is very basic and all it does is asks me the IP of the device, then logs in and displays the output of the command, in this case “show ap summary”.

from netmiko import ConnectHandler
ipaddr = input('IP:''')

net_connect =  ConnectHandler(ip = ipaddr,
                        port = 22,
                        username = 'admin',
                        password = 'mypassword',
                        device_type = 'cisco_wlc_ssh')

net_connect.find_prompt()
'(Cisco Controller) >'
output = net_connect.send_command('show ap summary')
print(output)
net_connect.disconnect()

Next code goes a little further and runs two commands and saves the output to a text file.

#This will dump AP summary and CDP information for all APs in a text file

from netmiko import ConnectHandler
import sys

def sh_ap_sumcdp():

	ipaddr = input('IP:''')
	net_connect =  ConnectHandler(ip = ipaddr,port = 22,username = 'admin',password = 'mypassword',device_type = 'cisco_wlc_ssh')
	net_connect.find_prompt()
	'(Cisco Controller) >'
	cmd = 'show ap summary'
	output = net_connect.send_command(cmd)
	sys.stdout = open('wlccon.txt', 'w')
	print(output)
	cmd = 'show ap cdp ne all'
	output = net_connect.send_command(cmd)
	print(output)

sh_ap_sumcdp()

Currently I am not able to make this work over VPN connections for some reason. And it seems to fail even locally if I am using a VPN for some reason. There is much more to learn and improve but this is just a first step. I am certain there are better ways to do this, so please feel free to leave feedback or any tips so that I can improve.

I used the following sources as a starting point and get some inspiration from.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

WordPress SEO