task 6.1 · chapter 6 of 8: netmiko · 30 min
Log in to r1 from Python
objective
Write connect() and interface_table() in netlab/devices.py: log in to a device with Netmiko, the username and password read from .env, and get show ip interface brief back as a list of dicts. Then run the script that prints r1’s interfaces.
netlab/devices.pyopen a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter
| The device | r1 (CapeOS Bolt, device_type cisco_ios), at 172.80.111.11; r1 resolves by name |
|---|---|
| The login | LAB_USER and LAB_PASSWORD in .env, read by netlab/env.py: load_env() |
| The script | scripts/r1_interfaces.py: given, it calls your two functions |
| The rule | the lab’s password must not appear anywhere in your code |
new to this? step by stepbeginner
cat .env: the login is there. (No.env?make setupmakes it.)- In the REPL:
from netmiko import ConnectHandler, then log in to r1 with the values fromos.environand tryfind_prompt(). - Write
connect()innetlab/devices.py(TODO 6.1a) the same way. - Challenge:
interface_table()(TODO 6.1b), one line withuse_textfsm=True. python scripts/r1_interfaces.py, thenmake check T=6.1.
more in meet the lab
SSH from code
What Netmiko does
Netmiko logs in to a network device over SSH and runs CLI commands for you. Underneath it is paramiko,
the Python SSH library. On top, Netmiko does what you’d do at a terminal: it learns the prompt, turns paging
off (terminal length 0) so long output doesn’t stop at --More--, and waits for the prompt to come back
before it hands you a command’s output.
ConnectHandler() opens the session and returns a connection object. Its methods, functions you call
with a dot, do the work: conn.find_prompt(), conn.send_command("show ..."), conn.disconnect().
in one sentence ConnectHandler(...) logs in; conn.send_command(...) runs a command; conn.disconnect() logs out.
device_type
Netmiko needs to know which CLI it’s talking to. CapeOS Bolt behaves like the CLI Netmiko calls cisco_ios,
so r1, r2 and sw1 are device_type="cisco_ios". The same name tells ntc-templates which template to use when
you add use_textfsm=True, and then send_command() returns a list of dicts instead of text.
The password lives in .env
The code names an environment variable, never the value: os.environ["LAB_PASSWORD"]. The value is in
.env, a file Git ignores, and load_env() reads it into os.environ. The check proves it two ways: it looks
for the lab’s password in your code, and it sets a wrong LAB_PASSWORD and expects your connect() to be
refused.
in one sentence If changing the environment doesn’t change what your code logs in with, the password is still in the code.
Netmiko on r1
A login in the REPL, and the same command twice, as text and parsed:
>>> conn = ConnectHandler(device_type="cisco_ios", host="r1", username=os.environ["LAB_USER"], password=os.environ["LAB_PASSWORD"])
>>> conn.find_prompt()
'r1#'
>>> rows = conn.send_command("show ip interface brief", use_textfsm=True)
>>> type(rows), len(rows)
(<class 'list'>, 6)
>>> rows[1]
{'interface': 'GigabitEthernet1', 'ip_address': '192.168.10.1', 'status': 'up', 'proto': 'up'}
The finished script:
$ python scripts/r1_interfaces.py
logged in to r1#
GigabitEthernet0 172.80.111.11 up/up
GigabitEthernet1 192.168.10.1 up/up
GigabitEthernet2 10.0.12.1 up/up
GigabitEthernet3 10.0.13.1 up/up
GigabitEthernet4 unassigned administratively down/down
Loopback0 10.255.0.1 up/up
And what the check says about a connect() that works but has the password typed into it:
_________________________ test_no_password_in_the_code _________________________
checks/test_6_1.py:8: in test_no_password_in_the_code
assert "capeos-lab" not in f.read_text(), f"the lab's password is written in {f.relative_to(ROOT)}: read it from the environment"
E AssertionError: the lab's password is written in netlab/devices.py: read it from the environment
...
__________________ test_credentials_come_from_the_environment __________________
checks/test_6_1.py:30: in test_credentials_come_from_the_environment
with pytest.raises(NetmikoAuthenticationException):
E Failed: DID NOT RAISE NetmikoAuthenticationException
2 failed, 2 passed in 3.18s
DID NOT RAISE means the check gave it a wrong password and the login still worked.
connect()
Look at the login the lab gave you:
run in the terminalcat .envLAB_USERandLAB_PASSWORDare the two you need. (LAB_API_URLandLAB_API_TOKENare for chapter 7.)Try it in the REPL first. Start
pythonin the repository’s folder, then:>>> import os >>> from netmiko import ConnectHandler >>> from netlab.env import load_env >>> load_env() >>> conn = ConnectHandler(device_type="cisco_ios", host="r1", username=os.environ["LAB_USER"], password=os.environ["LAB_PASSWORD"]) >>> conn.find_prompt() 'r1#' >>> print(conn.send_command("show ip interface brief")) >>> conn.disconnect()The login takes a second or two. If it fails, the last line of the traceback says why: Authentication (the login) or TCP connection (the device didn’t answer).
Now put the same thing in
connect(). Opennetlab/devices.pyand find TODO 6.1a.os,ConnectHandlerandload_envare already imported at the top. Replace theraise NotImplementedError(...)line:editnetlab/devices.pyCtrl+P → devices.pydef connect(host, device_type="cisco_ios"): """...the docstring stays as it is...""" load_env() return ConnectHandler( device_type=device_type, host=host, username=os.environ["LAB_USER"], password=os.environ["LAB_PASSWORD"], conn_timeout=5, )conn_timeout=5gives up after 5 seconds if nothing answers on port 22, instead of Netmiko’s default 10.Try your function. In a new REPL (so it imports your saved file):
>>> from netlab.devices import connect >>> conn = connect("r1") >>> conn.find_prompt() 'r1#' >>> conn.disconnect()
in one sentence connect() reads the login from the environment every time it’s called, so the check can change it underneath.
interface_table()
Write interface_table(conn) (TODO 6.1b): given a connection, return show ip interface brief parsed by
ntc-templates, as a list of dicts. Then run the given script:
python scripts/r1_interfaces.py
It should print r1’s six interfaces, the way the show stage does.
hint
send_command() takes one more argument that hands the output to ntc-templates before returning it.
hint
The connection already knows its device_type, so ntc-templates knows which template to pick. You pass only
the command and use_textfsm=True.
show the solutionnetlab/devices.py
or pull it into your lab: make solve T=6.1, then git diff --staged shows what changed
def connect(host, device_type="cisco_ios"):
load_env()
return ConnectHandler(
device_type=device_type,
host=host,
username=os.environ["LAB_USER"],
password=os.environ["LAB_PASSWORD"],
conn_timeout=5,
)
def interface_table(conn):
return conn.send_command("show ip interface brief", use_textfsm=True)
interface_table() takes a connection rather than a host, so the caller logs in once and can run several
commands on the same session. That’s how scripts/r1_interfaces.py uses it: connect(), find_prompt(),
interface_table(), then disconnect(). The check compares what the script prints with what r1 says at that
moment, so it would notice if you’d copied the table from the show stage.
5 check: run it, then prove it
$ make check T=6.1when it's right, you'll see
task 6.1 checks/test_6_1.py
checks/test_6_1.py::test_no_password_in_the_code PASSED [ 25%]
checks/test_6_1.py::test_the_script PASSED [ 50%]
checks/test_6_1.py::test_credentials_come_from_the_environment PASSED [ 75%]
checks/test_6_1.py::test_interface_table PASSED [100%]
============================== 4 passed in 2.49s ===============================
✓ task 6.1 done