⚡ IT Wisdom I told my team to fix the broken DNS server. It took a while, but they finally came around.
Skilled Practitioner
4249 XP 1751 to Expert
Units
Whetting Your Appetite — Why Python for Networking? Using the Python Interpreter An Informal Introduction to Python — Network Basics Control Flow — Making Decisions in Network Scripts Data Structures — Modeling Network Inventories Modules — Organizing Your Network Scripts Input and Output — Reading and Writing Network Data Errors and Exceptions — Building Reliable Network Scripts Classes — Modeling Network Devices as Objects Standard Library Part I — Tools Every Network Script Needs Standard Library Part II — Logging, Formatting, and Counting Virtual Environments and Packages — Isolating Your Dependencies Capstone — Build a Network Inventory Tool

The Standard Library

Python ships with hundreds of modules — no pip install required. This unit covers six that appear constantly in network automation scripts.


os — Filesystem Operations

import os

print(os.getcwd())                    # current working directory
print(os.listdir("."))                # list all files in current dir
os.makedirs("backups/2025", exist_ok=True)  # create nested dirs
print(os.path.exists("devices.json"))  # True or False
print(os.path.join("configs", "sw-core-01.cfg"))  # configs/sw-core-01.cfg

os.path.join() builds paths correctly across operating systems. exist_ok=True prevents an error if the directory already exists.


sys — Script Arguments

import sys

print(sys.argv)        # list of command-line arguments
print(sys.argv[0])     # the script name itself
print(sys.argv[1])     # first argument passed in

Run python3 script.py HQ and sys.argv is ['script.py', 'HQ']. Use sys.exit(1) to stop the script with a non-zero exit code on error.


glob — Find Files by Pattern

import glob

configs = glob.glob("configs/*.cfg")
print(configs)
# ['configs/sw-core-01.cfg', 'configs/rtr-edge-01.cfg']

backups = glob.glob("backups/**/*.json", recursive=True)

glob matches filename patterns just like shell wildcards. ** with recursive=True searches subdirectories.


re — Regular Expressions

Regular expressions match patterns in strings. In network automation they extract hostname parts, validate IPs, and parse log output.

import re

hostname = "sw-core-01"
match = re.match(r"^(sw|rtr|fw)-(\w+)-(\d+)$", hostname)
if match:
    print(match.group(1))   # sw
    print(match.group(2))   # core
    print(match.group(3))   # 01

re.match() anchors at the start of the string. re.search() finds a match anywhere. re.findall() returns all matches as a list.

Named groups make extraction readable:

pattern = r"^(?P<type>sw|rtr|fw)-(?P<role>\w+)-(?P<num>\d+)$"
match = re.match(pattern, "rtr-edge-01")
if match:
    print(match.group("type"))   # rtr
    print(match.group("role"))   # edge
    print(match.group("num"))    # 01

datetime — Timestamps for Logs and Reports

from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# 2025-04-15 09:30:00

stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"backup_{stamp}.cfg"
# backup_20250415_093000.cfg

Use strftime() to format timestamps. Common format codes: %Y year, %m month, %d day, %H hour (24h), %M minute, %S second.


math — Subnet Calculations

import math

hosts_needed = 50
bits = math.ceil(math.log2(hosts_needed + 2))  # +2 for network and broadcast
prefix = 32 - bits
print(f"Need /{prefix} subnet")   # Need /26 subnet

math.log2() returns the base-2 logarithm. math.ceil() rounds up to the nearest integer.


Summary

  • os — list, create, and check files and directories
  • sys — access command-line arguments with sys.argv
  • glob — find files matching a wildcard pattern
  • re — extract and validate strings with regular expressions
  • datetime — format timestamps for logs and report filenames
  • math — logarithm and ceiling for subnet host calculations