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.
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.
- Log insession cookiekept
- Readdevice listas JSON
- Keepfour fieldsper device
- WriteCSV filewith a header
- Reportdevices thatare not up
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.
| Setting | Where it lives | Why |
|---|---|---|
| Manager address | SDWAN_MANAGER environment variable | Changes between lab and production without editing code |
| User name | SDWAN_USER environment variable | A read-only account is enough for this script |
| Password | SDWAN_PASS, or a secrets store | Not in the file, the history or the notes |
| Certificate check | On, which is the default | Protects the login in transit |
| Output file | inventory.csv in the working folder | Dated copies make changes visible |
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.
| Part of the script | Protects against | Without it |
|---|---|---|
| Timeout on every request | A busy Manager that does not answer | The script hangs for hours |
| raise_for_status | A 4xx or 5xx status being treated as data | An error page is parsed as a result |
| Login page check | A failed login that returns status 200 | An empty file that looks like success |
| get with an empty default | A device with a missing field | One KeyError stops the whole run |
| Settings from the environment | Credentials in the file or the history | A password in version control |
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.
Run it and read the result
$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)
$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
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.
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.
| Device | Change | What it suggests |
|---|---|---|
| BR-01 | None | Nothing to do |
| BR-02 | reachable to unreachable | A device that went down since Monday; look at it first |
| BR-09 | New row, no system IP, unreachable | A device added to the Manager that has not connected yet |
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.
$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 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.
- SymptomKeyError: 'system-ip'The whole run stopped
- New dataBR-09 added yesterdayNo system address yet
- AssumptionEvery device has every fieldSquare brackets fail on a gap
- FixUse get with an empty defaultReport it 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.
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.
- Controlconnectionsper device
- TunnelsBFD sessionsper device
- Versionssoftwareper device
- Recordone datedfile per run
| Pitfall | What happens | Habit |
|---|---|---|
| One request per device with no pause | A large fabric produces a burst of calls | Add a short delay and run in a quiet period |
| No timeout or retry limit | One slow call blocks the run | Set a timeout and retry a few times only |
| Results that are limited or paged | The file holds only part of the data | Check the API documentation for limits |
| Certificate check turned off | The login can be intercepted | Keep the check on; add a private authority if needed |
| Files stored anywhere | Device and site details spread | Keep them with the other network records |
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.
| Devices | Calls per run | Time at one second a call |
|---|---|---|
| 50 | 151 | 2 min 31 s |
| 200 | 601 | 10 min 1 s |
| 400 | 1,201 | 20 min 1 s |
| 1,000 | 3,001 | 50 min 1 s |
Learn more: SD-WAN Manager REST API StructureSD-WAN Manager WorkflowsMonitoring Dashboard
Test yourself
The script stops with KeyError: 'system-ip' the morning after a branch was added. What is the best fix?
A call returns status 200, and the body starts with an HTML page. What should the script do?
Which account should the script use?
The script will fetch tunnel state for 400 devices, one call each. What is a sensible habit?
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?
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?
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?