6.1 Interpret basic Python code used for network automation

ENCOR 350-401 v1.2 · 6.0 Automation and Artificial Intelligence

ENCOR expects you to read short Python scripts that automate network tasks: variables and data types, lists and dictionaries, loops and conditions, functions, and libraries such as requests, ncclient and netmiko. You do not write large programs; you say what a given script does and spot its mistakes.

What you must know

A typical script

import requests

BASE = "https://catalyst-center.example.com/dna"

def get_token(user, password):
    r = requests.post(f"{BASE}/system/api/v1/auth/token", auth=(user, password), timeout=10)
    r.raise_for_status()
    return r.json()["Token"]

token = get_token("api-ro", "…")
headers = {"X-Auth-Token": token, "Accept": "application/json"}
devices = requests.get(f"{BASE}/intent/api/v1/network-device", headers=headers, timeout=10).json()["response"]

for d in devices:
    if d["reachabilityStatus"] != "Reachable":
        print(f"{d['hostname']:20} {d['managementIpAddress']:15} UNREACHABLE")
  1. get_token posts the credentials with basic authentication and returns the Token field of the JSON answer; raise_for_status() stops on a 4xx or 5xx.
  2. headers is a dictionary; the token goes in X-Auth-Token.
  3. .json()["response"] is a list of dictionaries, one per device.
  4. The loop prints each device whose reachabilityStatus is not Reachable, aligned in columns with f-strings.

One API call returns the whole inventory (1); the loop does the filtering.

Building blocks to recognise

CodeMeaning
vlans = [10, 20, 30]A list; vlans[0] is 10
intf = {"name": "Gi1", "up": True}A dictionary; intf["name"] is "Gi1"
for v in vlans:Loop over each item
if x == 1: … elif …: … else: …Conditions
def f(a, b=2): return a + bA function with a default argument
try: … except requests.exceptions.Timeout: …Handle an error
json.loads(text) / json.dumps(obj, indent=2)JSON text to Python data and back

Commands

python3 script.pyRun a script.
pip install requests netmiko ncclientInstall the usual network libraries.

Exam traps

Check yourself

data = {"interfaces": [{"name": "Gi1"}, {"name": "Gi2"}]}: what is data["interfaces"][1]["name"]?
"Gi2".
What does r.raise_for_status() do?
Raises an exception if the HTTP response is a 4xx or 5xx error.
Which library would you use to send CLI commands over SSH?
Netmiko (or Paramiko).

More topics in 6.0 Automation and Artificial Intelligence