Netmiko exceptions, try/except per device & csv.DictWriter

Handle failures and write a report

Lesson 7 of 20 · 15 min · Module 2: Read the network

On a real network something is always switched off or still has an old password. A good script records the problem and carries on with the next device.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Tell a timeout from a failed login
  • Keep going after one device fails
  • Write a CSV report with DictWriter

The idea

Netmiko raises NetmikoTimeoutException when a device does not answer (wrong address, device down, a firewall in the way) and NetmikoAuthenticationException when it answers but rejects the login. Put the try inside the loop, so one failure only affects one device, and catch these two exceptions by name. csv.DictWriter writes the report: give it the column names, call writeheader(), then writerow() with a dictionary per device.

from netmiko import ConnectHandler, NetmikoTimeoutException

try:
    with ConnectHandler(**device) as conn:
        print(conn.find_prompt())
except NetmikoTimeoutException:
    print(device["host"], "did not answer")

01A device that does not answer

sw4 in Cluj is switched off today. Netmiko waits, then raises NetmikoTimeoutException. Its message starts with the reason.

import os
from netmiko import (ConnectHandler, NetmikoAuthenticationException,
                     NetmikoTimeoutException)

USERNAME = os.environ["NET_USERNAME"]
PASSWORD = os.environ["NET_PASSWORD"]

try:
    ConnectHandler(device_type="cisco_ios", host="10.0.1.11",
                   username=USERNAME, password=PASSWORD)
except NetmikoTimeoutException as error:
    print(type(error).__name__)
    print(str(error).splitlines()[0])
Output
NetmikoTimeoutException
TCP connection to device failed.

02A login that fails

sw5 answers, but someone forgot to update its password. That is a different exception, so the report can say what went wrong.

try:
    ConnectHandler(device_type="huawei", host="10.0.1.12",
                   username=USERNAME, password=PASSWORD)
except NetmikoAuthenticationException as error:
    print(type(error).__name__)
    print(str(error).splitlines()[0])
Output
NetmikoAuthenticationException
Authentication to device failed.

03Rows to CSV

DictWriter matches each dictionary key to its column. newline="" stops Python from adding blank lines on some systems.

import csv

with open("demo.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "status"])
    writer.writeheader()
    writer.writerow({"name": "sw4", "status": "unreachable"})
print(open("demo.csv").read())
Output
name,status
sw4,unreachable

Your turn

Try to log in to every device in devices.csv. Write report.csv with the columns name, host, status and prompt, one row per device in file order. The status is ok (with the device prompt), unreachable after a timeout, or login failed after an authentication error; the prompt stays empty for failures.

What the checks look for

  • report.csv has the four columns
  • Every device has a row, in file order
  • The statuses are right
  • Working devices show their prompt
  • Catches the two Netmiko exceptions by name
Try it in the editor →

Take this with you

Catch the expected failures per device, record them, and keep going.

Go a little further

Log in to the devices in parallel with concurrent.futures.ThreadPoolExecutor and executor.map, and check that the report is the same, in the same order.

Learn Network Automation for free

20 short lessons with real code and instant checks.

See the whole course →