#!/usr/bin/env python3 """Example script for: High-Throughput SNMP Counter Ingestion into TimescaleDB Source: https://carlkidcrypto.github.io/blog/ezsnmp-data-logger-timescaledb-counter-ingestion.html """ import os from concurrent.futures import ProcessPoolExecutor, as_completed from datetime import datetime, timezone from typing import Any, List import pg8000.native from ezsnmp import Session from ezsnmp.exceptions import ConnectionError, GenericError, TimeoutError OID_SYS_UPTIME = "1.3.6.1.2.1.1.3.0" OID_IF_DESCR = "1.3.6.1.2.1.2.2.1.2" OID_HC_IN_OCTETS = "1.3.6.1.2.1.31.1.1.1.6" OID_HC_OUT_OCTETS = "1.3.6.1.2.1.31.1.1.1.10" def safe_int(val: Any, default: int = 0) -> int: digits = "".join(c for c in str(val) if c.isdigit() or c == "-") return int(digits) if digits and digits != "-" else default def poll_switch(host: str, community: str = "public") -> List[dict]: ts = datetime.now(timezone.utc) rows: List[dict] = [] with Session( hostname=host, community=community, version=2, timeout=2, retries=1, set_max_repeaters_to_num=25, print_enums_numerically=True, ) as session: try: uptime_var = session.get(OID_SYS_UPTIME)[0] uptime_cs = ( safe_int(uptime_var.value) if uptime_var.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE") else 0 ) descrs = { v.index: v.value for v in session.bulk_walk(OID_IF_DESCR) if v.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE") } in_octs = { v.index: safe_int(v.value) for v in session.bulk_walk(OID_HC_IN_OCTETS) if v.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE") } out_octs = { v.index: safe_int(v.value) for v in session.bulk_walk(OID_HC_OUT_OCTETS) if v.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE") } for idx, descr in descrs.items(): if idx not in in_octs or idx not in out_octs: continue rows.append( { "ts": ts, "host": host, "if_index": safe_int(idx), "if_descr": descr, "uptime": uptime_cs, "in_oct": in_octs[idx], "out_oct": out_octs[idx], } ) except (TimeoutError, ConnectionError, GenericError) as err: print(f"[{host}] SNMP poll error: {err}") return rows def ingest_fleet(hosts: List[str]) -> None: batch: List[dict] = [] with ProcessPoolExecutor(max_workers=4) as pool: futures = {pool.submit(poll_switch, h): h for h in hosts} for fut in as_completed(futures): batch.extend(fut.result()) if not batch: return conn = pg8000.native.Connection( user=os.environ["DB_USER"], password=os.environ["DB_PASSWORD"], host=os.environ.get("DB_HOST", "localhost"), port=int(os.environ.get("DB_PORT", "5432")), database=os.environ.get("DB_NAME", "net_telemetry"), ) try: insert_sql = """ INSERT INTO snmp_interface_counters ( time_stamp, host, if_index, if_descr, sys_uptime_cs, in_octets, out_octets ) VALUES ( :ts, :host, :if_index, :if_descr, :uptime, :in_oct, :out_oct ) ON CONFLICT (time_stamp, host, if_index) DO NOTHING """ for row in batch: conn.run(insert_sql, **row) print(f"[+] Inserted {len(batch)} interface counter samples.") finally: conn.close()