Course contents

Unit 10: Automation and observabilityLesson 10.3 (2 of 2 in this unit)50 of 63 in the Advanced Cisco SD-WAN course

Python API inventory and state extraction

A short read-only Python script that logs in to the Manager, extracts the device inventory to a CSV, stops on a login page, and copes with devices that have missing fields.

Advanced · 18 min read

You'll learn to write and read a small Python script that logs in to the Manager, extracts the device inventory to a CSV, stops loudly when a call does not return JSON, and handles devices with missing fields.

Technical definition

State extraction means reading the fabric's current facts through the API and keeping the parts you need in a form that can be compared over time. A first extraction is the device inventory: names, system addresses, sites and reachability. Run on a schedule, the saved files show what changed and when.

What the script is for

The first useful automation is one that only reads. It logs in, asks the Manager for the device inventory, keeps a few fields and writes them to a file, then says which devices are not reachable. It cannot change the fabric, so a mistake costs a wrong report and not an outage, and the dated file is a record to compare with the next run.

Diagram
What the script does
What the script does

It logs in, reads the device inventory, keeps four fields for each device, writes a CSV file and reports the devices that are not reachable.

  1. Log insession cookiekept
  2. Readdevice listas JSON
  3. Keepfour fieldsper device
  4. WriteCSV filewith a header
  5. Reportdevices thatare not up
Each step can fail in its own way, and the script checks the two that fail quietly: the login and the reply.

The script was run against a local stand-in that returns the same shape of reply as the examples in this lesson. It has not been run against a real Manager, so test it against a lab Manager first and check the paths against the API documentation for your release.

Settings and credentials

The script needs three settings: the address of the Manager, a user name and a password. Keep them out of the script file and out of the command line, where they end up in shell history and backups. An environment variable, set by the person or the scheduler that runs the script, is the simplest place for a first version, and a secrets store is better for a shared one.

Diagram
Where each setting lives
Where each setting lives
SettingWhere it livesWhy
Manager addressSDWAN_MANAGER environment variableChanges between lab and production without editing code
User nameSDWAN_USER environment variableA read-only account is enough for this script
PasswordSDWAN_PASS, or a secrets storeNot in the file, the history or the notes
Certificate checkOn, which is the defaultProtects the login in transit
Output fileinventory.csv in the working folderDated copies make changes visible
Give the script an account with a read-only role, so that a bug or a stolen password cannot change the fabric.

The script

import csv import os import sys import requests BASE = os.environ["SDWAN_MANAGER"] # for example https://manager.example.com USER = os.environ["SDWAN_USER"] PASSWORD = os.environ["SDWAN_PASS"] FIELDS = ["host-name", "system-ip", "site-id", "reachability"] def looks_like_login_page(reply): return reply.text.lstrip().lower().startswith("<html") def login(session): reply = session.post( f"{BASE}/j_security_check", data={"j_username": USER, "j_password": PASSWORD}, timeout=30, ) reply.raise_for_status() if looks_like_login_page(reply): sys.exit("Login failed: the Manager returned its login page") def get_json(session, path): reply = session.get(f"{BASE}{path}", timeout=30) reply.raise_for_status() if looks_like_login_page(reply): sys.exit("Session not accepted: got the login page instead of JSON") return reply.json() def main(): with requests.Session() as session: login(session) devices = get_json(session, "/dataservice/device")["data"] rows = [{name: device.get(name, "") for name in FIELDS} for device in devices] with open("inventory.csv", "w", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=FIELDS) writer.writeheader() writer.writerows(rows) down = [row for row in rows if row["reachability"] != "reachable"] print(f"Wrote inventory.csv with {len(rows)} devices") for row in down: print(f"Not reachable: {row['host-name']} ({row['system-ip'] or 'no system IP yet'})") if __name__ == "__main__": main()

Python 3 with the requests library. Save as inventory.py and set the three environment variables first. The paths and field names are those of the example in this lesson, so confirm them in the API documentation of your release.

Read it in four parts. The first part reads the settings. The second logs in and refuses to continue if the Manager answers with its login page. The third reads the device list and applies the same login-page check to the reply, with a timeout on every request. The last part keeps four fields for each device with get, writes the CSV and prints the devices that are not reachable.

Diagram
What each part protects against
What each part protects against
Part of the scriptProtects againstWithout it
Timeout on every requestA busy Manager that does not answerThe script hangs for hours
raise_for_statusA 4xx or 5xx status being treated as dataAn error page is parsed as a result
Login page checkA failed login that returns status 200An empty file that looks like success
get with an empty defaultA device with a missing fieldOne KeyError stops the whole run
Settings from the environmentCredentials in the file or the historyA password in version control
Each line exists because the failure it prevents is quiet. A loud failure is easy to fix; a quiet one produces a wrong file.
Diagram
Fail loudly or keep going
Fail loudly or keep going

Stopping with a clear message at a login page protects the reader of the file. Carrying on writes an empty or wrong inventory that looks like a real one.

Stop with a messageLogin page returnedBad status codeMissing settings
Carry onA field is missingfor one deviceWrite an empty value
The script stops on the two quiet failures and carries on through the one harmless one, a missing field.

Run it and read the result

Example output written for this lesson, simplified; real responses have many more fields and differ between releases
$python3 inventory.py
Wrote inventory.csv with 3 devices
Not reachable: BR-02 (10.255.1.12)
Not reachable: BR-09 (no system IP yet)
Three devices were read and one file was written. BR-02 is a real fault to look at. BR-09 has no system address yet, which usually means it has been added to the Manager and has not connected for the first time. The two lines mean different things, and the script keeps them apart.
Example output written for this lesson, simplified; real responses have many more fields and differ between releases
$cat inventory.csv
host-name,system-ip,site-id,reachability
BR-01,10.255.1.11,11,reachable
BR-02,10.255.1.12,12,unreachable
BR-09,,19,unreachable
The file has a header row and one row per device. Save a copy with the date in its name after each run, and a plain text comparison of two files shows which devices appeared, disappeared or changed state.
Diagram
Two kinds of not reachable
Two kinds of not reachable

A device that has a system address and is not reachable is a fault to look at. A device with no system address yet has usually been added to the Manager and has not connected for the first time.

Real faultHas a system IPBR-02 is not up
Not yet connectedNo system IP yetBR-09 is new
The script prints both, and the wording of each line tells them apart.

Compare each day's file with the one before. The table compares two example files: Monday's, with BR-01 and BR-02 both reachable, and Tuesday's, the file shown above.

Diagram
What comparing two runs shows
What comparing two runs shows
DeviceChangeWhat it suggests
BR-01NoneNothing to do
BR-02reachable to unreachableA device that went down since Monday; look at it first
BR-09New row, no system IP, unreachableA device added to the Manager that has not connected yet
Worked out by script from the two example files. A device that is missing from the newer file may have been removed from the Manager, which is worth a check as well.

A worked case: the run that stopped on one device

An earlier version of the script read each field with square brackets. It worked for months, then stopped on the morning after a new branch was added to the Manager.

Example output written for this lesson, simplified; real responses have many more fields and differ between releases
$python3 inventory.py
Traceback (most recent call last):
  File "inventory.py", line 41, in main
    rows = [{name: device[name] for name in FIELDS} for device in devices]
KeyError: 'system-ip'
The error names the missing field. The new device, BR-09, has no system address yet, so the lookup failed and the whole run stopped. Nothing is wrong with the fabric. The script assumed that every device has every field.
Diagram
Evidence from the case
Evidence from the case

The script stopped with a KeyError for system-ip, the device list contains a newly added branch, that branch has not connected yet and has no system address, and the script assumed every field exists.

  1. SymptomKeyError: 'system-ip'The whole run stopped
  2. New dataBR-09 added yesterdayNo system address yet
  3. AssumptionEvery device has every fieldSquare brackets fail on a gap
  4. FixUse get with an empty defaultReport it as not yet connected
The fix is in the script, not the fabric: read optional fields with get and report the device as not yet connected.

Growing the script

The inventory call returns one list for the whole fabric, so it is one request. State for each device, such as control connections or tunnel sessions, usually needs one request per device. The same checks apply to every extra call, and the number of calls starts to matter in a large fabric.

Diagram
From inventory to state extraction
From inventory to state extraction

The inventory gives the list of devices. For each device, further read calls can fetch control connections, tunnel sessions and software versions, and the results join into one dated record.

Inventory loop
  • Controlconnectionsper device
  • TunnelsBFD sessionsper device
  • Versionssoftwareper device
  • Recordone datedfile per run
Look up each call in the API documentation for your release, and add the checks from the first script to every one.
Diagram
Checks that matter as the script grows
Checks that matter as the script grows
PitfallWhat happensHabit
One request per device with no pauseA large fabric produces a burst of callsAdd a short delay and run in a quiet period
No timeout or retry limitOne slow call blocks the runSet a timeout and retry a few times only
Results that are limited or pagedThe file holds only part of the dataCheck the API documentation for limits
Certificate check turned offThe login can be interceptedKeep the check on; add a private authority if needed
Files stored anywhereDevice and site details spreadKeep them with the other network records
A small, careful script that is trusted is worth more than a large one that nobody checks.

The number of calls grows with the fabric. The table counts one inventory call plus three calls per device, for control connections, tunnel sessions and software versions, with half a second for each reply and half a second of pause.

Diagram
How long a growing script runs
How long a growing script runs
DevicesCalls per runTime at one second a call
501512 min 31 s
20060110 min 1 s
4001,20120 min 1 s
1,0003,00150 min 1 s
Worked out by script from example timings. Real reply times vary, and the Manager may limit request rates, so read the guide for your release. Prefer a call that returns many devices at once where the API offers one.

Learn more: SD-WAN Manager REST API StructureSD-WAN Manager WorkflowsMonitoring Dashboard

Test yourself

Predict · scenario 1

The script stops with KeyError: 'system-ip' the morning after a branch was added. What is the best fix?

Predict · scenario 2

A call returns status 200, and the body starts with an HTML page. What should the script do?

Predict · scenario 3

Which account should the script use?

Predict · scenario 4

The script will fetch tunnel state for 400 devices, one call each. What is a sensible habit?

Predict · scenario 5

A fabric has 200 devices. The script makes one inventory call plus three calls per device, and each call takes 0.5 s for the reply and 0.5 s of pause. About how long does one run take?

Predict · scenario 6

Monday's file shows BR-02 reachable. Tuesday's shows BR-02 unreachable, plus a new BR-09 row with no system IP. Which reading is best?

Predict · scenario 7

A device in the reply has no reachability field at all. The script reads it with get and an empty default, and reports devices whose value is not reachable. What happens to that device?

FAQ

Why does the script stop when it gets a login page?
A login page served with status 200 looks like a success to code that checks only the status. Stopping with a clear message is better than writing an empty or wrong file that someone trusts later.
Why read fields with get instead of square brackets?
A device that was just added, or one of a different kind, may not have every field yet. Square brackets stop the whole run with a KeyError for one missing field, while get returns an empty value so the rest of the inventory is still written.
Should the script switch off certificate checking?
No. The requests library checks the Manager certificate by default, and that check protects the credentials in transit. If the Manager uses a private certificate authority, point the script at that authority's certificate rather than turning the check off.
Is the inventory file sensitive?
It can be. It names devices, sites and system addresses, and a longer extraction may include serial numbers. Store it where the network team's other records are kept and avoid sharing it in open chat or tickets.