# py312
# requirements:
# pynetbox==7.9.0
from typing import Literal, Optional, TypedDict
import pynetbox
class netbox(TypedDict):
url: str
token: str
def api(auth: netbox):
# pynetbox adds /api itself; the resource URL may already end with it.
return pynetbox.api(
auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
)
def keep(**fields):
# The run form sends "" / [] / {} for untouched fields: drop them.
return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
def page(records):
# One page (limit/offset), as NetBox's count plus the raw records.
results = [dict(r) for r in records]
return {"count": len(records), "results": results}
def main(
auth: netbox,
device_id: Optional[int] = None,
name: Optional[str] = None,
enabled: Optional[Literal["any", "true", "false"]] = None,
q: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
):
"""
List Interfaces
List interfaces, optionally of one device, by name or enabled state.
"""
records = api(auth).dcim.interfaces.filter(
**keep(
device_id=device_id,
name=name,
enabled=None if enabled == "any" else enabled,
q=q,
),
# limit=0 means NetBox's MAX_PAGE_SIZE, which also caps an explicit 1000.
limit=50 if limit is None else limit or 1000,
offset=offset or 0,
)
return page(records)
Submitted by hugo989 3 hours ago