Python for Network Automation
Scripting Network Tasks, Monitoring & Report Generation
Why Automate Network Operations?
Manual network operations are slow, error-prone, and do not scale. Python has become the
de-facto language for network automation because of libraries like Netmiko, Paramiko, NAPALM,
and the Requests library for REST APIs. Automation reduces MTTR, eliminates repetitive CLI
work, and enables consistent configuration management across hundreds of devices.
Core Python Libraries for NetOps
Library Use Case
Netmiko SSH to network devices (Cisco, Juniper, Arista, etc.)
Paramiko Low-level SSH2 implementation; base for Netmiko
NAPALM Vendor-agnostic network config get/set
Requests REST API calls (SD-WAN, cloud platforms)
Scapy Packet crafting and analysis
Nornir Parallel task execution across device inventory
TextFSM / ntc-templates Structured parsing of CLI output
Page 1 of 5 | Python for Network Automation
SSH Automation with Netmiko
Netmiko abstracts vendor-specific SSH quirks and provides a uniform interface for sending
commands and receiving structured output.
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'host': '[Link]',
'username': 'admin',
'password': 'secret',
with ConnectHandler(**device) as net_connect:
output = net_connect.send_command('show ip interface brief')
print(output)
Sending Configuration Commands
config_commands = [
'interface GigabitEthernet0/1',
'description UPLINK-TO-CORE',
'ip address [Link] [Link]',
'no shutdown',
output = net_connect.send_config_set(config_commands)
net_connect.save_config() # 'write mem'
Always use save_config() after configuration changes to persist to NVRAM. For bulk operations
across many devices, iterate over a device inventory dictionary or use Nornir for parallel execution.
Page 2 of 5 | Python for Network Automation
Parsing Output with TextFSM & RegEx
Raw CLI output is unstructured text. TextFSM templates (via ntc-templates) convert it into Python
lists of dictionaries, which can then be processed, stored in a database, or used to generate
reports.
Using ntc-templates
from netmiko import ConnectHandler
# use_textfsm=True triggers ntc-template parsing
output = net_connect.send_command(
'show ip arp',
use_textfsm=True
# output is now a list of dicts:
# [{'address': '[Link]', 'mac': 'aabb.cc00.0100', ...}]
for entry in output:
print(entry['address'], entry['mac'])
Writing a Custom RegEx Parser
When no template exists, use Python's re module. Example: extract interface names and their
status from 'show interfaces status' output:
import re
pattern = r'(\S+)\s+(connected|notconnect)\s+(\d+|trunk)'
matches = [Link](pattern, raw_output)
for iface, status, vlan in matches:
print(f'{iface}: {status} (VLAN {vlan})')
Page 3 of 5 | Python for Network Automation
Automated Reporting with Python
After collecting and parsing network data, Python makes it easy to generate reports in multiple
formats: CSV via the csv module, HTML emails via smtplib + jinja2, or PDFs via reportlab. This is
directly applicable to NOC shift handover automation.
CSV Report Generation
import csv
data = [{'host': 'R1', 'cpu': 34, 'mem': 55},
{'host': 'R2', 'cpu': 78, 'mem': 40}]
with open('[Link]', 'w', newline='') as f:
writer = [Link](f, fieldnames=['host','cpu','mem'])
[Link]()
[Link](data)
HTML Email via win32com (Windows/Outlook)
import [Link]
outlook = [Link]('[Link]')
mail = [Link](0)
[Link] = 'team@[Link]'
[Link] = 'NOC Shift Handover Report'
[Link] = 'Open TicketsDetails here'
[Link]()
Use [Link]() if running in a thread. SMTP AUTH is often disabled in Office 365
tenants, making win32com the preferred sending method on Windows environments.
Page 4 of 5 | Python for Network Automation
REST APIs & Watchdog Automation
Calling REST APIs with Requests
import requests
headers = {'Authorization': 'Bearer TOKEN',
'Content-Type': 'application/json'}
resp = [Link](
'[Link]
headers=headers, timeout=10
devices = [Link]()['data']
Folder Watchdog for Triggered Automation
from [Link] import Observer
from [Link] import FileSystemEventHandler
import time
class Handler(FileSystemEventHandler):
def on_created(self, event):
if event.src_path.endswith('.csv'):
process_file(event.src_path)
observer = Observer()
[Link](Handler(), path='C:/NOC/exports', recursive=False)
[Link]()
try:
while True: [Link](5)
except KeyboardInterrupt:
[Link]()
The watchdog pattern is ideal for automating NOC workflows: drop a CSV export from your
ticketing system into a folder and Python automatically processes and emails the report.
Page 5 of 5 | Python for Network Automation