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.
netlab/devices.pyopen a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter
| The devices | r1 .11, r2 .12, sw1 .21 (cisco_ios) and r3 .13 (arista_eos), on 172.80.111.0/24 |
|---|---|
| The script | scripts/collect.py: given; it builds the four Devices and calls your collect() |
| The problem | make break T=6.2 gives r2 a different password; make reset puts it back |
| Your error | DeviceError, already defined at the top of netlab/devices.py |
new to this? step by stepbeginner
- Replace
Device = None(TODO 6.2a) with a dataclass of three fields:name,host,device_type. - Challenge:
collect(devices)(TODO 6.2b): for each device,connect(),send_command(..., use_textfsm=True),disconnect(). python scripts/collect.py: four lines, one per device.make break T=6.2, run the script again: oneerror:line, no traceback. Thenmake check T=6.2andmake reset.
more in meet the lab
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.
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.
The Device dataclass
Open
netlab/devices.pyand find TODO 6.2a.dataclassis already imported. ReplaceDevice = Nonewith 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.pywritesDevice("r3", "172.80.111.13", "arista_eos").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. TwoDevices 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.
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
DeviceErrortoo, naming the device (the check tries anr9at 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.2when 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