online posts 16
python 101 for network engineers

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.

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 devicer1 (CapeOS Bolt, device_type cisco_ios), at 172.80.111.11; r1 resolves by name
The loginLAB_USER and LAB_PASSWORD in .env, read by netlab/env.py: load_env()
The scriptscripts/r1_interfaces.py: given, it calls your two functions
The rulethe lab’s password must not appear anywhere in your code
new to this? step by stepbeginner
  1. cat .env: the login is there. (No .env? make setup makes it.)
  2. In the REPL: from netmiko import ConnectHandler, then log in to r1 with the values from os.environ and try find_prompt().
  3. Write connect() in netlab/devices.py (TODO 6.1a) the same way.
  4. Challenge: interface_table() (TODO 6.1b), one line with use_textfsm=True.
  5. python scripts/r1_interfaces.py, then make check T=6.1.

more in meet the lab

1 explain

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.

2 show

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.

3 follow along

connect()

  1. Look at the login the lab gave you:

    run in the terminal
    cat .env
    

    LAB_USER and LAB_PASSWORD are the two you need. (LAB_API_URL and LAB_API_TOKEN are for chapter 7.)

  2. Try it in the REPL first. Start python in 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).

  3. Now put the same thing in connect(). Open netlab/devices.py and find TODO 6.1a. os, ConnectHandler and load_env are already imported at the top. Replace the raise NotImplementedError(...) line:

    editnetlab/devices.pyCtrl+P → devices.py
    def 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=5 gives up after 5 seconds if nothing answers on port 22, instead of Netmiko’s default 10.

  4. 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.

4 challenge

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:

run in the terminal
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.1

when 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