Skip to content
Guides & References

Write an SIE script in Python

How to write an SIE script in Python: the standard library for APIs and JSON, a virtual environment for extra libraries, and a minimal script.

Script Integration EngineUpdated
On this page

Write an SIE script in Python

Python is the most flexible choice for SIE. The standard library alone handles HTTP, JSON, XML, archives and hashing, so many scripts need nothing installed. When you do need a library such as Netmiko, it goes in a virtual environment the web user can read.


Good for

  • REST APIs, JSON and XML.
  • Cleaning, sorting and flattening output before it’s stored.
  • Anything with more logic than a few commands.

Set it up

For the standard library only, use the system Python: /usr/bin/python3. For extra libraries, make a virtual environment outside the rConfig folder:

Terminal window
sudo python3 -m venv /opt/rconfig-sie/venv
sudo /opt/rconfig-sie/venv/bin/pip install <library>
sudo chmod -R a+rX /opt/rconfig-sie
sudo -u apache /opt/rconfig-sie/venv/bin/python -c "import <library>" # www-data on Ubuntu

Get your server ready for scripts has the full steps.


The command

/usr/bin/python3 {script_path}my-script.py {device_ip} {device_username} {device_password}

Use /opt/rconfig-sie/venv/bin/python instead when the script imports a library from the virtual environment.


A minimal script

This one reads a JSON config from an HTTPS API with Basic authentication, using only the standard library:

python-skeleton.py
#!/usr/bin/env python3
"""Minimal SIE script in Python: fetch a JSON config over HTTPS.
Usage:
python-skeleton.py <host> <username> <password>
"""
import base64
import json
import sys
import urllib.error
import urllib.request
URL = "https://{host}/api/config" # adapt for your device
def note(message):
print(message, file=sys.stderr)
def fail(message):
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def main():
if len(sys.argv) < 4:
fail("usage: python-skeleton.py <host> <username> <password>")
host, user, password = sys.argv[1:4]
auth = base64.b64encode(f"{user}:{password}".encode()).decode()
request = urllib.request.Request(URL.format(host=host), headers={
"Authorization": f"Basic {auth}", "Accept": "application/json"})
note(f"fetching config from {host}")
try:
with urllib.request.urlopen(request, timeout=30) as response:
data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as e:
fail(f"HTTP {e.code} from {host}")
except urllib.error.URLError as e:
fail(f"cannot reach {host}: {e.reason}")
except json.JSONDecodeError:
fail(f"{host} did not return JSON")
if not data:
fail("empty config, refusing to store it")
json.dump(data, sys.stdout, indent=2, sort_keys=True)
sys.stdout.write("\n")
note(f"SIE-OK: python config from {host}")
return 0
if __name__ == "__main__":
sys.exit(main())

Habits that matter in Python

  • print(..., file=sys.stderr) for everything except the config. A stray print() while debugging ends up in the stored config.
  • sort_keys=True on every json.dump. Key order otherwise follows the API, which can change between runs.
  • Catch errors and turn them into ERROR: lines. An unhandled exception prints a traceback and exits 1, which fails the run, but the reason is harder to read.
  • Share helpers. A module saved in the scripts folder, such as sie_clean.py from the cleaning output recipe, can be imported by any script there.

Recipes that use Python

Type to search.