Introduction to Python – Data Structures (Input and Output)

Categories Devnet, Python
  • You can format the data that is output from python. The data can be returned as human readable output, the data can be returned to a file to be used later. This can be done through expression statements, the print() function or using the write() method for file objects.

Oh, you Fancy! huh?

  • Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.
  • Formatted string literals, also known as f-strings allow you to include the value of an expression inside a string. The format is to start with an f or F before the string and adding curles to the expression ie: {expression}
  • An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:
  • Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.
  • There are many other formats you can use on literal strings.

String() Format Method()

  • The str.format() method works as follows:

Introduction to Python – Modules

Categories Python, Windows

You can follow along with the code at Github.

  • A module in Python allows you to put definitions in a file and use them in a script or in an interactive instance of the interpreter.
  • Definitions from a module can be imported into other modules or into the main module.
  • I have created a module named which we will import into the interpreter and Visual Studio Code.
  • The module must be in the same path or have the path specified for it to be imported.
  • NOTE: You can import modules in the interpreter.
  • Example of importing the module using VS Code.

Introduction to Python – Data Structures (Tuples)

Categories Python

You can follow along with the code from Github.

  • A tuple consists of a number of values separated by commas.

Tuple Packing and Unpacking

  • In Python we can pack the tuple by putting values into a new tuple
  • Unpacking a tuple is when we extract its values into a single variable.

List Vs Tuples

  • Lists are mutable – They can be changed or modified after creation according to the developers needs.
  • Tuples are immutable – they can’t be changed or modified after creation.
  • List have more operations (functions) available to them.
  • Syntax is different
  • A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

Introduction to Python – Data Structures (Lists)

Categories Python
  • Data structures are used to store a collection of related data. There are four built-in data structures in Python – list, tuple, dictionary and set.
  • ***NOTE: It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.***

Lists as Stacks

  • The last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.

Lists as Queues

  • The first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
  • To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends.
  • Notice the queues only can pop from left to right.

List Comprehensions

  • <+Make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
  • Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects.
  • A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal.
  • Notice that the order of the for and in statements are in the same order in both of the examples.

Methods for List Objects

  • append – Used to add an object to the end of a list.
    ***Notice append will only take one argument at a time.***
  • extend – Extends a list by adding all items from the iterable.
    ***Notice the difference between append and extend.***
  • insert – Inserts the object into a list at a given index. (0 = beginning of the list)
  • remove – Removes an object from a list. You must specify the object to be removed. If it is a string you must specify the sting.

Clear – Clears all objects out of a list.

  • index – locate and search for an object within the list starting at a given index.

Introduction to Python – Function Arguments

Categories Python

  • An argument (also known as an arg) is data that can be push into a function.
  • The function must be called with the exact number of arguments that it is expecting. Notice the error received.
  • The code also uses the ‘in’ keyword. This keyword tests whether or not a sequence contains a specific value. The values are evaluated at the function definition within the defining scope.
  • Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. One can think of the keyword arguments (kwargs) as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
  • The form is kwarg=value
  • Now notice when we call the function with the proper number of arguments we no longer receive the error.
  • ***The reason we are not having to pass the ‘reminder’ argument is explained next.***

Default Arguments

  • Default arguments are used so that a function can be called with fewer arguments than it is defined to allow.
  • In the past example we needed to pass the argument ‘retries’ or else we would receive an error.
  • Now if we change our default value the number of times the function iterates is different. Why?
  • Notice that the default value is evaluated only once.
  • when the default is a mutable object such as a list, dictionary, or instances of most classes the function accumulates the arguments passed to it on subsequent calls.

Introduction to Python – Interpreter

Categories Python
  • Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.


  • The interactive interpreter can be used by executing the version of python you are running. Executing python3 will drop you into whatever version of python 3 you have installed.
  • Python can do basic to complex mathematics functions built into the interpreter.
  • You MUST define a variable in order to call it.

More Fun With The Interpreter

  • Take a moment to see the output from each input.

Hello World

  • You don’t have to use the interpreter but do be aware of it.
  • In the below screenshot we are using Visual Studio Code and running the script in interpreter after.

Napalm and Cisco IOS

Categories Automation, Cisco, Devnet, Python

Copy and pasta into a text file name it CHANGES.cfg

vlan 999
default int ra fa 1/0/10 - 20
int ra fa 1/0/10 - 20
sw mo acc
sw acc vlan 999
vlan 120
name TEST

Copy and pasta into a text file name it whatever you like with a .py python extension.

import json
from netmiko import ConnectHandle
from napalm import get_network_driver

driver = get_network_driver('ios')
c3750 = driver('','lab','lab')

print ('Accessing..')

print ('Comparing Config Changes to Current Running Configuration.')
diffs = c3750.compare_config()
if len(diffs) > 0:
print('No changes needed.')

print ('Saving Config..')
print ('Config Saved..')
print ('Connection Closed..')

Netmiko: Configure multiple devices with multiple commands (Cisco IOS)

Categories Automation, Cisco, Devnet

Create a script and save it as
Create a text file with your IOS script inside – This example is named c3750_lab_design

Save the file in the same folder path you save the script.

Example of Cisco IOS Script:

vtp mode transparent
spanning-tree mode rapid-pvst
udld enable
errdisable recovery cause all
port-channel load-balance src-dst-ip
ip name-server
no ip http server
no ip http secure-server

snmp-server community python1 RO
snmp-server community python2 RW

ntp server

clock timezone CST -6
clock summer-time CST recurring
service timestamps debug datetime msec localtime
service timestamps log datetime msec localtime

vlan 10
name Data
vlan 11
name Voice
vlan 12
name Test

interface vlan 1
description In-band Management

ip default-gateway
ip dhcp snooping vlan 100,101

no ip dhcp snooping information option
ip dhcp snooping
ip arp inspection vlan 10
spanning-tree portfast bpduguard default

interface range Fa 1/0/1 - 20
switchport access vlan 10
switchport voice vlan 11
switchport host
switchport port-security maximum 5
switchport port-security
switchport port-security aging time 5
switchport port-security aging type inactivity
switchport port-security violation restrict
ip arp inspection limit rate 100
ip dhcp snooping limit rate 100
ip verify source

interface range Fa 1/0/21 - 48
switch tr en do
switchport mode trunk

Configure multiple Cisco IOS devices with Netmiko

Categories Automation, Cisco, Devnet

Related Posts:

Copy pasta script and save as

from netmiko import ConnectHandler

c3750_s1 = {
'device_type': 'cisco_ios',
'ip': '',
'username': 'lab',
'password': 'lab'

c3750_s2 = {
'device_type': 'cisco_ios',
'ip': '',
'username': 'lab',
'password': 'lab'

c3750_s3 = {
'device_type': 'cisco_ios',
'ip': '',
'username': 'lab',
'password': 'lab'

all_devices = [c3750_s1, c3750_s2, c3750_s3]

for devices in all_devices:
net_connect = ConnectHandler(**devices)
for n in range (2,21):
print ("Creating VLAN " + str(n))
config_commands = ['vlan ' + str(n), 'name Python_VLAN' + str(n)]
output = net_connect.send_config_set(config_commands)
print (output)

Execute the script and then check the devices for configuration changes.