online posts 16
python 101 for network engineers

task 6.2 · chapter 6 of 8: netmiko · 40 min

Every device, and a login that fails

objective

Write a Device dataclass and collect(), which runs one command on r1, r2, sw1 and r3 (two device types) and returns every parsed table. When a login fails or a device doesn’t answer, raise DeviceError with one line that names the device, so scripts/collect.py prints that line instead of a traceback.

you edit, in the labnetlab/devices.py

open a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter

given
The devicesr1 .11, r2 .12, sw1 .21 (cisco_ios) and r3 .13 (arista_eos), on 172.80.111.0/24
The scriptscripts/collect.py: given; it builds the four Devices and calls your collect()
The problemmake break T=6.2 gives r2 a different password; make reset puts it back
Your errorDeviceError, already defined at the top of netlab/devices.py
new to this? step by stepbeginner
  1. Replace Device = None (TODO 6.2a) with a dataclass of three fields: name, host, device_type.
  2. Challenge: collect(devices) (TODO 6.2b): for each device, connect(), send_command(..., use_textfsm=True), disconnect().
  3. python scripts/collect.py: four lines, one per device.
  4. make break T=6.2, run the script again: one error: line, no traceback. Then make check T=6.2 and make reset.

more in meet the lab

1 explain

Objects of your own, and failures in one line

A dataclass

A class is a kind of object; Netmiko’s connection is one you’ve already used. A dataclass is the simplest class you can write yourself: a named group of fields, with Python writing the code that creates one, prints it and compares two of them.

@dataclass
class Device:
    name: str
    host: str

Device("r1", "172.80.111.11") makes one, and d.host reads a field. A field can have a default, like a function’s argument: device_type: str = "cisco_ios".

in one sentence A dataclass is a dict with fixed, named keys that you read with a dot.

Two device types, one function

r3 runs CapeOS Pulse, which Netmiko and ntc-templates know as arista_eos. If each Device carries its own device_type, the same connect() and send_command() work on all four devices: Netmiko picks a different class for r3, with the same methods. One thing does change: r3’s template has different keys (protocol where Bolt’s has proto). collect() returns each table as it comes, so that doesn’t matter here.

Catching what you can explain

A refused login raises NetmikoAuthenticationException; a device that doesn’t answer raises NetmikoTimeoutException (both are imported at the top of the file). Left alone, either one ends the script with two screens of traceback. Caught, it becomes one line that says which device and what to check.

raise NewError(...) from None raises your exception instead of the one you caught, without printing the original underneath.

in one sentence Catch the exceptions you can explain, and re-raise them as one line that names the device.

Always disconnect

A try: block with finally: runs the finally part whether the try part worked or raised. Put disconnect() there, and a command that fails still closes its SSH session.

2 show

Four devices, then one that says no

The finished script, with the lab as it starts:

$ python scripts/collect.py
r1   6 IP interfaces, 5 up
r2   6 IP interfaces, 5 up
sw1  10 IP interfaces, 4 up
r3   4 IP interfaces, 4 up

make break T=6.2 changes r2’s password:

  setting up task 6.2's problem

  r2        username admin privilege 15 secret not-the-lab-password
            r2 now refuses the lab's password: your code has to say so in one clear line

  make reset puts everything back.

The same script, now:

$ python scripts/collect.py
error: r2: login failed (check LAB_USER and LAB_PASSWORD)

It exits 1. Without the except, a refused login ends in Netmiko’s own traceback. Here’s the end of one, from a wrong password typed for r1 in the REPL:

netmiko.exceptions.NetmikoAuthenticationException: Authentication to device failed.

Common causes of this problem are:
1. Invalid username and password
2. Incorrect SSH-key file
3. Connecting to the wrong device

Device settings: cisco_ios r1:22

Clear enough once you know where to look, and it comes after thirty lines of paramiko’s and Netmiko’s code.

3 follow along

The Device dataclass

  1. Open netlab/devices.py and find TODO 6.2a. dataclass is already imported. Replace Device = None with the class:

    editnetlab/devices.pyCtrl+P → devices.py
    @dataclass
    class Device:
        name: str
        host: str
        device_type: str = "cisco_ios"
    

    The order of the fields is the order of the arguments: scripts/collect.py writes Device("r3", "172.80.111.13", "arista_eos").

  2. Try it in the REPL:

    >>> from netlab.devices import Device
    >>> d = Device("r3", "172.80.111.13", "arista_eos")
    >>> d
    Device(name='r3', host='172.80.111.13', device_type='arista_eos')
    >>> Device("r1", "172.80.111.11")
    Device(name='r1', host='172.80.111.11', device_type='cisco_ios')
    

    The second one took the default device_type. Two Devices with the same fields are ==, which a plain class wouldn’t give you without more code.

in one sentence @dataclass turns a list of fields into a class you can create, print and compare.

4 challenge

collect()

Write collect(devices, command="show ip interface brief") (TODO 6.2b). It returns a dict: {device name: parsed output}, one entry per device, using your connect() from task 6.1.

  • Parse with ntc-templates, and disconnect from each device when you’re done with it.
  • A refused login raises DeviceError("r2: login failed (check LAB_USER and LAB_PASSWORD)"), naming the device.
  • A device that doesn’t answer raises DeviceError too, naming the device (the check tries an r9 at 172.80.111.19, which doesn’t exist).

Run python scripts/collect.py with the lab as it is, then make break T=6.2 and run it again. make reset when you’re done.

hint

Start with the loop and no error handling: results = {}, then for each d in devices, connect(d.host, d.device_type), store send_command(command, use_textfsm=True) under results[d.name], disconnect(). Get the four lines first.

hint

Only connect() can raise the login and timeout exceptions, so the try: goes around that one line, with one except for each exception, each raising DeviceError(...) from None.

hint

Then a second try: around send_command(), with finally: conn.disconnect(). Don’t put the disconnect() in the first try: if connect() failed, there’s no conn to disconnect.

show the solutionnetlab/devices.py

or pull it into your lab: make solve T=6.2, then git diff --staged shows what changed

@dataclass
class Device:
    name: str
    host: str
    device_type: str = "cisco_ios"


def collect(devices, command="show ip interface brief"):
    results = {}
    for d in devices:
        try:
            conn = connect(d.host, d.device_type)
        except NetmikoAuthenticationException:
            raise DeviceError(f"{d.name}: login failed (check LAB_USER and LAB_PASSWORD)") from None
        except NetmikoTimeoutException:
            raise DeviceError(f"{d.name}: no answer from {d.host} on port 22") from None
        try:
            results[d.name] = conn.send_command(command, use_textfsm=True)
        finally:
            conn.disconnect()
    return results

collect() doesn’t print anything: it raises, and scripts/collect.py decides what to do with that (print error: and the message, and exit 1). Keeping the two apart lets the checker call your function directly, and lets lesson 8 decide differently: carry on past a failed device instead of stopping. The first failure still stops collect() here, so with the break in place, r1’s table is fetched and then thrown away when r2 refuses.

5 check: run it, then prove it

$ make check T=6.2

when it's right, you'll see

task 6.2  checks/test_6_2.py
checks/test_6_2.py::test_device_dataclass PASSED                         [ 20%]
checks/test_6_2.py::test_collect_every_device PASSED                     [ 40%]
checks/test_6_2.py::test_wrong_password PASSED                           [ 60%]
checks/test_6_2.py::test_no_answer PASSED                                [ 80%]
checks/test_6_2.py::test_the_script_says_it_clearly PASSED               [100%]
============================== 5 passed in 9.63s ===============================
✓ task 6.2 done