Device lists, for loops, find_prompt & collecting results

Many devices, one loop

Lesson 2 of 20 · 12 min · Module 1: First steps with automation

The point of automation is doing the same thing on many devices. A list of devices and a for loop turn one login into fifty.

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…

  • Loop over a list of devices
  • Read who answered from the prompt
  • Collect results in a dictionary

The idea

Keep the devices in a list and build each Netmiko dictionary inside the loop. Collect what you learn in a dictionary keyed by device, so the results stay together. find_prompt() shows who answered: Cisco prints sw1#, Huawei prints <sw3> in user view. strip() with a set of characters removes them from both ends.

for host in ["10.0.0.11", "10.0.0.12"]:
    device = {"device_type": "cisco_ios", "host": host,
              "username": USERNAME, "password": PASSWORD}
    with ConnectHandler(**device) as conn:
        print(host, conn.find_prompt())

01Two vendors, two prompts

The same method works on both vendors; only the device_type differs. Notice the prompts: sw1# on Cisco, <sw3> on Huawei.

import os
from netmiko import ConnectHandler

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

for host, device_type in [("10.0.0.11", "cisco_ios"), ("10.0.0.13", "huawei")]:
    device = {"device_type": device_type, "host": host,
              "username": USERNAME, "password": PASSWORD}
    with ConnectHandler(**device) as conn:
        print(conn.find_prompt())
Output
sw1#
<sw3>

02Strip the symbols

strip("#<>") removes any of those characters from both ends of the string, and nothing from the middle.

print("sw1#".strip("#<>"))
print("<sw3>".strip("#<>"))
Output
sw1
sw3

03One dictionary for the results

Assigning to results[key] inside the loop builds the dictionary step by step. Printing it at the end shows everything at once.

results = {}
for host in ["10.0.0.11", "10.0.0.12"]:
    results[host] = "checked"
print(results)
Output
{'10.0.0.11': 'checked', '10.0.0.12': 'checked'}

Your turn

Connect to the four Bucharest switches in switches (the last one is a Huawei device) and build hostnames, a dictionary that maps each address to the hostname shown in its prompt, without #, < or >. Print it.

What the checks look for

  • hostnames maps every address to its name
  • Logged in to all four switches
  • The result is printed
  • The password is not written in the code
Try it in the editor →

Take this with you

Put devices in a list, loop over it, and collect the results in a dictionary keyed by device.

Go a little further

Netmiko also keeps the hostname in conn.base_prompt. Use it instead of strip() and check that you get the same dictionary.

Learn Network Automation for free

20 short lessons with real code and instant checks.

See the whole course →