#!/usr/bin/env python3 """ Example client for the Roller Network Account Control Center REST API. Documentation: https://acc.rollernet.us/help/rest-api.php Needs Python 3.8 or later and the Requests package (pip install requests, or on Debian and Ubuntu: apt install python3-requests). Set your token in the environment, not on the command line, where other users of the system could see it: export RNACC_TOKEN='rnacc_...' ./rest-api-example.py domains Commands: domains list mail domains queue [DOMAIN] queued message counts, for all domains or one flush DOMAIN deliver a domain's queued mail now (ETRN) usertable DOMAIN show a domain's valid user table adduser DOMAIN ENTRY add an entry to the valid user table deluser DOMAIN ENTRY remove an entry from the valid user table zones list Secondary DNS zones retransfer ZONE transfer a Secondary DNS zone again logs TYPE START END [DOMAIN] mail log entries as JSON, for all domains or one logs-csv TYPE START END FILE [DOMAIN] mail log entries saved as a CSV file TYPE is incoming, delivery or submission; DOMAIN works with incoming and delivery only. START and END are times such as 2026-11-19T00:00, in UTC unless RNACC_TZ is set, or with their own offset such as 2026-11-19T00:00-08:00. Set RNACC_TZ to a time zone name such as America/Los_Angeles to use that zone for START and END and for the times shown. """ import json import os import sys import urllib.parse try: import requests except ImportError: sys.exit("This script needs the Requests package: pip install requests") API_URL = os.environ.get("RNACC_API_URL", "https://acc.rollernet.us/api/v1") # one session reuses the connection across requests session = requests.Session() class ApiError(Exception): pass def segment(value): """URL encode one path segment, such as a domain or mail box address.""" return urllib.parse.quote(value, safe="") def request(method, path, body=None, query=None, accept="application/json", save_to=None): """Send a request and return the decoded data member (None for a 204 response).""" token = os.environ.get("RNACC_TOKEN") if not token: raise ApiError("Set RNACC_TOKEN to your API token.") headers = {"Authorization": "Bearer " + token, "Accept": accept} try: # json= sends the body as JSON with Content-Type: application/json; # stream=True leaves a large mail log on the wire until it is read with session.request(method, API_URL + path, params=query, json=body, headers=headers, stream=True, timeout=(10, 120)) as resp: if not resp.ok: # errors are always JSON: {"error": {"status": ..., "message": ...}} try: message = resp.json()["error"]["message"] except (ValueError, KeyError, TypeError): message = resp.reason raise ApiError(f"HTTP {resp.status_code}: {message}") if save_to is not None: # write the file as it arrives instead of holding it in memory with open(save_to, "wb") as out: for chunk in resp.iter_content(chunk_size=65536): out.write(chunk) return None if resp.status_code == 204: return None try: result = resp.json() except ValueError: raise ApiError("The response is not valid JSON.") from None except requests.RequestException as e: raise ApiError(f"Unable to reach the API: {e}") from None # a large mail log result can fail after the response has started if "error" in result: raise ApiError("Incomplete result: " + result["error"]["message"]) return result.get("data") def log_path(log_type, domain=None): """The mail log path: one domain's log, or every domain's (and the submission log).""" if domain: return f"/mail/domains/{segment(domain)}/logs/{segment(log_type)}" return f"/mail/logs/{segment(log_type)}" def log_query(start, end): """The mail log query: the time range, and the time zone from RNACC_TZ when it is set.""" query = {"start": start, "end": end} if os.environ.get("RNACC_TZ"): query["tz"] = os.environ["RNACC_TZ"] return query def show(data): print(json.dumps(data, indent=2)) def main(argv): if not argv: print(__doc__.strip(), file=sys.stderr) return 2 command, args = argv[0], argv[1:] if command == "domains" and not args: show(request("GET", "/mail/domains")) elif command == "queue" and len(args) <= 1: path = f"/mail/domains/{segment(args[0])}/queue" if args else "/mail/queue" show(request("GET", path)) elif command == "flush" and len(args) == 1: request("POST", f"/mail/domains/{segment(args[0])}/queue/flush") print(f"Queue flush requested for {args[0]}.") elif command == "usertable" and len(args) == 1: show(request("GET", f"/mail/domains/{segment(args[0])}/usertable")) elif command == "adduser" and len(args) == 2: show(request("POST", f"/mail/domains/{segment(args[0])}/usertable/entries", body={"entry": args[1]})) elif command == "deluser" and len(args) == 2: request("DELETE", f"/mail/domains/{segment(args[0])}/usertable/entries/{segment(args[1])}") print(f"Removed {args[1]} from the valid user table for {args[0]}.") elif command == "zones" and not args: show(request("GET", "/dns/secondary/zones")) elif command == "retransfer" and len(args) == 1: request("POST", f"/dns/secondary/zones/{segment(args[0])}/retransfer") print(f"Zone transfer requested for {args[0]}.") elif command == "logs" and len(args) in (3, 4): path = log_path(args[0], args[3] if len(args) == 4 else None) show(request("GET", path, query=log_query(args[1], args[2]))) elif command == "logs-csv" and len(args) in (4, 5): path = log_path(args[0], args[4] if len(args) == 5 else None) request("GET", path, query=log_query(args[1], args[2]), accept="text/csv", save_to=args[3]) print(f"Saved {args[3]}.") else: print(__doc__.strip(), file=sys.stderr) return 2 return 0 if __name__ == "__main__": try: sys.exit(main(sys.argv[1:])) except ApiError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1)