When I started automating my network, what helped me most wasn't a 500-page book, but a single sheet with the essentials in plain sight. That's what you have here: 12 Python building blocks, each with one key idea, examples you can run, a short challenge and the chapter of Python for Everyone where you can go deeper. At the end you can download it all as a PDF sheet.
The idea comes from Eric Matthes's Beginner's Python Cheat Sheet (Python Crash Course, No Starch Press), which I recommend you read. My version is updated to Python 3.14 and brought into networking: the examples talk about routers, interfaces, VLANs, IP addresses and inventories, so you can go from not knowing how to code (your point A) to reading and writing your first automation scripts (your point B).
Download the PDF sheet. All 12 building blocks on a single sheet, ready to print and keep next to you while you write your first scripts.
Variables, strings and f-strings
A variable is a label that points to a value. With f-strings you build text from those variables, without adding strings together with +.
You can try everything on this page in the REPL: type python3 (or py on Windows) in your terminal and go line by line. If you've never opened it, check the REPL section in chapter 1 or the REPL video on YouTube.
hostname = "core-01"
interfaces = 48
version = 17.9
print(hostname, interfaces, version)
A string is text in quotes. Put an f in front and everything you write inside curly braces is replaced by its value. Methods like upper() or strip() give you back a new string.
sitio = "lima"
equipo = f"{hostname}.{sitio}"
print(equipo.upper())
print(f"{equipo} has {interfaces} interfaces")
print(" Gi0/1 ".strip())
core-01 48 17.9
CORE-01.LIMA
core-01.lima has 48 interfaces
Gi0/1
Challenge. Create two variables for a VLAN, its number (10) and its name ("users"), and print VLAN 10: USERS with an f-string.
Show the solution
vlan_id = 10
nombre = "users"
print(f"VLAN {vlan_id}: {nombre.upper()}")Go deeper: Chapter 3 · Basic types
Lists
A list stores several values in order, like the router inventory of a site. You access each one by its position.
Indexes start at 0: the first item is [0]. Negative indexes count from the end, so [-1] is always the last one. With append() you add an item to the end.
routers = ["core-01", "dist-01", "acc-01"]
print(routers[0])
print(routers[-1])
routers.append("acc-02")
print(routers)
print(len(routers))
core-01
acc-01
['core-01', 'dist-01', 'acc-01', 'acc-02']
4
Challenge. Create the list vlans = [10, 20, 30], add VLAN 99 and show the last item without writing its exact position.
Show the solution
vlans = [10, 20, 30]
vlans.append(99)
print(vlans[-1]) # 99Go deeper: Chapter 4 · Collections
Looping through lists
With a for loop you repeat the same action for each item: exactly what you do when you configure twenty identical interfaces.
The for line ends with a colon, and everything indented below it repeats for each item.
interfaces = ["Gi0/1", "Gi0/2", "Gi0/3", "Gi0/4"]
for intf in interfaces:
print(f"interface {intf}")
print(" no shutdown")
range() generates numbers, slicing [start:end] takes a piece of the list and a comprehension builds a new list in a single line. To copy a list use [:]: if you write copia = interfaces you only create another name for the same list.
for vlan in range(10, 41, 10):
print(f"vlan {vlan}")
uplinks = interfaces[:2]
print(uplinks)
ids = [n * 10 for n in range(1, 5)]
print(ids)
copia = interfaces[:]
copia.append("Gi0/5")
print(len(interfaces), len(copia))
interface Gi0/1
no shutdown
interface Gi0/2
no shutdown
interface Gi0/3
no shutdown
interface Gi0/4
no shutdown
vlan 10
vlan 20
vlan 30
vlan 40
['Gi0/1', 'Gi0/2']
[10, 20, 30, 40]
4 5
Challenge. With a single comprehension, generate the list of ports from Gi0/1 to Gi0/8.
Show the solution
puertos = [f"Gi0/{n}" for n in range(1, 9)]
print(puertos)Go deeper: Chapter 5 · Control flow
Tuples
A tuple is like a list you can't change. Use it for data that belongs together and shouldn't move, like an IP and its prefix.
You write it with parentheses and read it just like a list. The best part is unpacking it: you assign each value to its own variable in a single line. If you try to change an item, Python answers with a TypeError.
gateway = ("192.168.1.1", 24)
print(gateway[0])
ip, prefijo = gateway
print(f"{ip}/{prefijo}")
vecinos = [("dist-01", "Gi0/1"), ("dist-02", "Gi0/2")]
for equipo, puerto in vecinos:
print(f"{equipo} connected via {puerto}")
192.168.1.1
192.168.1.1/24
dist-01 connected via Gi0/1
dist-02 connected via Gi0/2
Challenge. Store VLAN 20 and its name "voice" in a tuple, unpack it and print vlan 20 name voice.
Show the solution
vlan = (20, "voice")
numero, nombre = vlan
print(f"vlan {numero} name {nombre}")Go deeper: Chapter 4 · Collections
Conditionals
Comparisons return True or False, and with if, elif and else you decide what your script does based on the state of the network.
Compare with ==, !=, <, >=; combine with and, or and not. With in and not in you ask whether a value is in a list.
estado = "up"
print(estado == "up")
mtu = 1500
print(1500 <= mtu <= 9216)
vlans = [10, 20, 30]
print(20 in vlans, 99 not in vlans)
ssh_activo = False
print(not ssh_activo)
Python checks the conditions from top to bottom and runs only the first block that is true.
cpu = 87
if cpu >= 90:
print("CRITICAL")
elif cpu >= 75:
print("WARNING")
else:
print("OK")
True
True
True True
True
WARNING
Challenge. If VLAN 40 isn't in vlans, add it and print VLAN 40 created; if it's already there, print VLAN 40 already exists.
Show the solution
vlans = [10, 20, 30]
if 40 not in vlans:
vlans.append(40)
print("VLAN 40 created")
else:
print("VLAN 40 already exists")Go deeper: Chapter 5 · Control flow
Dictionaries
A dictionary stores key-value pairs: the natural format of an inventory or of a network API response.
You read a value by its key. If the key might not exist, use get() with a default value and you avoid the KeyError. To add one, assign a new key. items() loops through pairs, keys() through keys only and values() through values only.
router = {"hostname": "core-01", "model": "C8300", "ios": "17.9"}
print(router["hostname"])
print(router.get("serial", "no data"))
router["site"] = "Lima"
for clave, valor in router.items():
print(f"{clave}: {valor}")
inventario = {"core-01": "10.0.0.1", "dist-01": "10.0.0.2"}
print(list(inventario.keys()))
for ip in inventario.values():
print(f"ping {ip}")
core-01
no data
hostname: core-01
model: C8300
ios: 17.9
site: Lima
['core-01', 'dist-01']
ping 10.0.0.1
ping 10.0.0.2
Challenge. Add "dist-02": "10.0.0.3" to the inventory and loop through it with items() to print dist-02 -> 10.0.0.3 for each device.
Show the solution
inventario = {"core-01": "10.0.0.1", "dist-01": "10.0.0.2"}
inventario["dist-02"] = "10.0.0.3"
for equipo, ip in inventario.items():
print(f"{equipo} -> {ip}")Go deeper: Chapter 4 · Collections
User input
With input() your script asks the person running it a question. What you get back is always text: if you need a number, convert it.
int() converts to an integer and float() to a decimal. If you forget to convert, "10" + 1 ends in a TypeError. Inside an f-string you can format the value: :.1f keeps one decimal place.
hostname = input("Hostname: ")
vlan = int(input("VLAN: "))
uso = float(input("Link usage in %: "))
print(f"{hostname}: VLAN {vlan}, next free {vlan + 1}")
print(f"Free capacity: {100 - uso:.1f} %")
Hostname: core-01
VLAN: 10
Link usage in %: 72.5
core-01: VLAN 10, next free 11
Free capacity: 27.5 %
Challenge. Ask how many ports a switch has and show how many are still free if you already use 30.
Show the solution
puertos = int(input("Switch ports: "))
print(f"Free ports: {puertos - 30}")Go deeper: Chapter 2 · My first Python program
While loops
A while loop repeats as long as its condition is true. It's useful for retries and for small menus that wait for a command.
With a counter you control how many times it loops. Don't forget to update it inside the loop, or it never ends.
intento = 1
while intento <= 3:
print(f"Ping to 10.0.0.1, attempt {intento}")
intento += 1
You can also repeat until the user types quit, just like on a device console.
comando = ""
while comando != "quit":
comando = input("THoR> ")
if comando != "quit":
print(f"Running: {comando}")
Ping to 10.0.0.1, attempt 1
Ping to 10.0.0.1, attempt 2
Ping to 10.0.0.1, attempt 3
THoR> show version
Running: show version
THoR> show ip route
Running: show ip route
THoR> quit
Challenge. Rewrite the console with while True and break, without repeating the comparison with "quit".
Show the solution
while True:
comando = input("THoR> ")
if comando == "quit":
break
print(f"Running: {comando}")Go deeper: Chapter 5 · Control flow
Functions
A function packages a task under its own name so you write it once and use it many times, for example to generate an interface configuration.
You define it with def. Arguments with a default value are optional, return gives back the result and the docstring, the string on the first line, explains what it does.
def configurar_interfaz(nombre, descripcion, estado="no shutdown"):
"""Returns the configuration lines of an interface."""
return f"interface {nombre}\n description {descripcion}\n {estado}"
print(configurar_interfaz("Gi0/1", "UPLINK-CORE"))
print(configurar_interfaz("Gi0/2", "UNUSED", estado="shutdown"))
def contar_activas(estados):
"""Counts how many interfaces are up."""
return estados.count("up")
activas = contar_activas(["up", "down", "up", "up"])
print(f"Active interfaces: {activas}")
print(contar_activas.__doc__)
interface Gi0/1
description UPLINK-CORE
no shutdown
interface Gi0/2
description UNUSED
shutdown
Active interfaces: 3
Counts how many interfaces are up.
Challenge. Write crear_vlan(numero, nombre="NO-NAME") that returns vlan 10 and, on the next line, name USERS. Test it with and without a name.
Show the solution
def crear_vlan(numero, nombre="NO-NAME"):
"""Returns the configuration of a VLAN."""
return f"vlan {numero}\n name {nombre}"
print(crear_vlan(10, "USERS"))
print(crear_vlan(99))Go deeper: Chapter 6 · Functions
Classes
A class is a blueprint: it defines what data a router has and what it can do. Each concrete router is an object created from that blueprint.
__init__ runs when the object is created and stores its attributes in self. Methods are functions that live inside the class.
class Router:
"""A router in the inventory."""
def __init__(self, hostname, ip):
self.hostname = hostname
self.ip = ip
self.interfaces = []
def agregar_interfaz(self, nombre):
self.interfaces.append(nombre)
print(f"{self.hostname}: {nombre} added")
r1 = Router("core-01", "10.0.0.1")
r1.agregar_interfaz("Gi0/0")
print(r1.ip)
With inheritance, RouterBorde gets everything from Router and adds its own. super() calls the parent class's __init__ so you don't repeat code.
class RouterBorde(Router):
"""Router that also speaks BGP with the provider."""
def __init__(self, hostname, ip, asn):
super().__init__(hostname, ip)
self.asn = asn
def resumen(self):
return f"{self.hostname} ({self.ip}) AS {self.asn}"
borde = RouterBorde("edge-01", "203.0.113.1", 65001)
borde.agregar_interfaz("Gi0/1")
print(borde.resumen())
core-01: Gi0/0 added
10.0.0.1
edge-01: Gi0/1 added
edge-01 (203.0.113.1) AS 65001
Challenge. Create a Switch class that inherits from Router, adds a vlans list and an agregar_vlan() method.
Show the solution
class Switch(Router):
"""Access switch with its VLANs."""
def __init__(self, hostname, ip):
super().__init__(hostname, ip)
self.vlans = []
def agregar_vlan(self, numero):
self.vlans.append(numero)
sw = Switch("acc-01", "10.0.1.1")
sw.agregar_vlan(10)
print(sw.hostname, sw.vlans) # acc-01 [10]Go deeper: Chapter 7 · Object orientation
Files
Reading and writing files lets you review saved configurations and leave backups or logs of what your script did.
Always open files with with: the file closes on its own when the block ends. Add encoding="utf-8" so accented characters read the same on Windows, Linux and macOS. Suppose you have core-01.cfg with this content:
hostname core-01
interface Gi0/1
description UPLINK
interface Gi0/2
shutdown
with open("core-01.cfg", encoding="utf-8") as archivo:
for linea in archivo:
linea = linea.rstrip()
if linea.startswith("interface"):
print(linea)
Mode "w" creates the file or wipes what it had; mode "a" appends to the end without touching what was there.
with open("respaldo.txt", "w", encoding="utf-8") as archivo:
archivo.write("hostname core-01\n")
with open("respaldo.txt", "a", encoding="utf-8") as archivo:
archivo.write("ntp server 10.0.0.100\n")
with open("respaldo.txt", encoding="utf-8") as archivo:
print(archivo.read(), end="")
interface Gi0/1
interface Gi0/2
hostname core-01
ntp server 10.0.0.100
Challenge. Count how many lines of core-01.cfg contain the word shutdown.
Show the solution
with open("core-01.cfg", encoding="utf-8") as archivo:
apagadas = sum(1 for linea in archivo if "shutdown" in linea)
print(f"Lines with shutdown: {apagadas}") # 1Go deeper: Chapter 12 · Input/output and files
Exceptions
An exception is an error that happens while the program runs. With try and except you catch it and decide what to do, instead of letting the script crash.
In try goes what can fail, in except what you do if it fails and in else what should only happen if everything went well.
texto = "ten"
try:
vlan = int(texto)
except ValueError:
print(f"'{texto}' is not a valid VLAN number")
else:
print(f"VLAN {vlan} ready")
The standard library's ipaddress module validates IPv4 and IPv6 addresses for you: if the text isn't an IP, it raises ValueError.
import ipaddress
def validar_ip(texto):
try:
ip = ipaddress.ip_address(texto)
except ValueError:
print(f"{texto}: invalid address")
else:
print(f"{texto}: valid IPv{ip.version}")
for candidata in ["192.168.1.10", "10.0.0.256", "2001:db8::1"]:
validar_ip(candidata)
'ten' is not a valid VLAN number
192.168.1.10: valid IPv4
10.0.0.256: invalid address
2001:db8::1: valid IPv6
Challenge. Ask for the gateway IP with input() and keep asking until it's valid.
Show the solution
import ipaddress
while True:
texto = input("Gateway IP: ")
try:
gateway = ipaddress.ip_address(texto)
except ValueError:
print("That's not a valid IP, try again.")
else:
break
print(f"Gateway: {gateway}")Go deeper: Chapter 10 · Exceptions
Simple is better than complex
Type import this in the REPL and Python shows you its philosophy, The Zen of Python (PEP 20). My favorite line for anyone who automates networks is the third one: Simple is better than complex.
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
With these 12 building blocks you already have what you need to write your first scripts. Now it's your turn: think of three network automation projects you want to build, for example a daily configuration backup, an IP address validator for your inventory or a VLAN configuration generator, and write them on the sheet. Start with the simplest one: that's your next point B.
What you take away
- F-strings are the modern way to build text: forget about concatenating with +.
- Lists, tuples and dictionaries cover almost any network inventory: order, fixed pairs and key-value.
- for loops through collections, while repeats until a condition changes and if-elif-else decides.
- Functions and classes let you write once and reuse on every device.
- Open files with with and encoding="utf-8", and validate what comes in with try/except and ipaddress.
Open the REPL, run one block a day and solve its challenge before you look at the solution.
Keep going with The House of Routing
If you want to go beyond the sheet, the free course Python for Everyone develops each block with more networking examples and challenges. And in November the daily «12 días de Python» series starts in Spanish: one block a day on my social channels and in your inbox. To join, message PY12 on Instagram or Facebook @thehouseofrouting.
Sources
- Beginner's Python Cheat Sheet (Python Crash Course)Eric Matthes · No Starch Press
- The Python Tutorialdocs.python.org
- ipaddress: IPv4/IPv6 manipulation librarydocs.python.org
- PEP 20: The Zen of Pythonpeps.python.org
Text by Jesús Espinoza, prepared with AI assistance and reviewed by him. Inspired by Eric Matthes's Beginner's Python Cheat Sheet.
