netbrain-auditor 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """NetBrain inventory auditing utilities."""
2
+ __version__ = "1.0.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,179 @@
1
+ """Inventory normalization, pagination and deterministic audit rules."""
2
+ import ipaddress
3
+ import json
4
+ import logging
5
+ from collections import Counter, defaultdict
6
+ from datetime import datetime, timezone
7
+ from .client import APIError, ci_get, require_list
8
+
9
+ LOG = logging.getLogger("netbrain_auditor")
10
+ EMPTY = {"", "n/a", "na", "none", "null", "unknown", "not available", "-", "not applicable"}
11
+ FIELDS = ["Device_ID", "Hostname", "Management_IP", "Device_Type", "Vendor", "Model",
12
+ "Serial", "Software_Version", "Site", "Location", "First_Discovery", "Last_Discovery",
13
+ "Age_Days", "Discovery_Status", "Audit_Status"]
14
+ FINDING_FIELDS = ["Device_ID", "Hostname", "Management_IP", "Category", "Finding",
15
+ "Severity", "Current_Value", "Recommended_Action"]
16
+ DUP_FIELDS = ["Type", "Value", "Device_Count", "Device_ID", "Hostname", "Management_IP"]
17
+
18
+
19
+ def value(record, *keys):
20
+ for key in keys:
21
+ v = ci_get(record, key)
22
+ if isinstance(v, (str, int, float)) and not isinstance(v, bool):
23
+ s = str(v).strip()
24
+ if s.casefold() not in EMPTY:
25
+ return s
26
+ return ""
27
+
28
+
29
+ def parse_date(raw):
30
+ try:
31
+ if isinstance(raw, dict):
32
+ raw = raw.get("$date")
33
+ if isinstance(raw, (int, float)) or (isinstance(raw, str) and raw.isdigit()):
34
+ n = float(raw)
35
+ return datetime.fromtimestamp(n / 1000 if abs(n) > 100_000_000_000 else n, timezone.utc)
36
+ if isinstance(raw, str):
37
+ dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
38
+ return dt.replace(tzinfo=dt.tzinfo or timezone.utc).astimezone(timezone.utc)
39
+ except (ValueError, OverflowError, OSError):
40
+ pass
41
+ return None
42
+
43
+
44
+ def get_date(record, *keys):
45
+ for key in keys:
46
+ parsed = parse_date(ci_get(record, key))
47
+ if parsed is not None:
48
+ return parsed
49
+ return None
50
+
51
+
52
+ def collect(client, page_size, progress):
53
+ rows = []
54
+ ids = set()
55
+ fingerprints = set()
56
+ total = None
57
+ while True:
58
+ payload = client.device_page(len(rows), page_size)
59
+ page = require_list(payload, "devices")
60
+ expected = ci_get(payload, "totalResultCount")
61
+ if expected is not None:
62
+ try:
63
+ if isinstance(expected, bool) or not str(expected).isdigit():
64
+ raise ValueError
65
+ expected = int(expected)
66
+ except (ValueError, TypeError):
67
+ raise APIError("Invalid totalResultCount") from None
68
+ if total is not None and expected != total:
69
+ raise APIError("Inventory count changed during pagination; rerun")
70
+ total = expected
71
+ if len(page) > page_size:
72
+ raise APIError("API returned more devices than requested")
73
+ if not page:
74
+ if total is not None and len(rows) != total:
75
+ raise APIError("Inventory ended before reported total")
76
+ break
77
+ fingerprint = json.dumps(page, sort_keys=True, ensure_ascii=False)
78
+ if fingerprint in fingerprints:
79
+ raise APIError("Repeated inventory page; pagination may be ignored")
80
+ fingerprints.add(fingerprint)
81
+ for rec in page:
82
+ ident = value(rec, "id", "deviceId", "devicesID")
83
+ if ident:
84
+ if ident in ids:
85
+ raise APIError("Repeated device ID during pagination; coverage uncertain")
86
+ ids.add(ident)
87
+ rows.extend(page)
88
+ progress(len(rows), total)
89
+ LOG.info("Inventory page: collected=%s reported_total=%s", len(rows), total)
90
+ if total is not None and len(rows) > total:
91
+ raise APIError("Collected count exceeds reported total")
92
+ if len(rows) > 1_000_000:
93
+ raise APIError("Inventory safety limit reached")
94
+ return rows, "COUNT_MATCHED" if total is not None else "PAGINATION_EXHAUSTED"
95
+
96
+
97
+ def normalize(rec, now, stale_days):
98
+ first = get_date(rec, "fDiscoveryTime", "firstDiscoveryTime", "firstDiscoverTime")
99
+ last = get_date(rec, "lDiscoveryTime", "lastDiscoveryTime", "lastDiscoverTime")
100
+ age = (now - last).days if last and last <= now else None
101
+ ip = value(rec, "mgmtIP", "managementIP", "ip")
102
+ try:
103
+ ip = str(ipaddress.ip_address(ip))
104
+ except ValueError:
105
+ pass
106
+ return dict(zip(FIELDS, [
107
+ value(rec, "id", "deviceId", "devicesID"), value(rec, "name", "hostname"),
108
+ ip, value(rec, "subTypeName", "deviceTypeName", "deviceType"),
109
+ value(rec, "vendor"), value(rec, "model"), value(rec, "sn", "serial", "serialNumber"),
110
+ value(rec, "ver", "softwareVersion", "osVersion"), value(rec, "site", "siteName"),
111
+ value(rec, "loc", "location"), first.isoformat() if first else "",
112
+ last.isoformat() if last else "", age if age is not None else "",
113
+ "UNKNOWN" if age is None else ("STALE" if age >= stale_days else "CURRENT"), "PASS"
114
+ ]))
115
+
116
+
117
+ def audit(records, stale_days, policy=None, now=None):
118
+ now = now or datetime.now(timezone.utc)
119
+ inventory = [normalize(x, now, stale_days) for x in records]
120
+ findings, duplicates, software = [], [], []
121
+ flagged = set()
122
+
123
+ def add(i, category, finding, severity, current, action):
124
+ d = inventory[i]
125
+ findings.append(dict(zip(FINDING_FIELDS, [d["Device_ID"], d["Hostname"],
126
+ d["Management_IP"], category, finding, severity, current, action])))
127
+ flagged.add(i)
128
+
129
+ for i, d in enumerate(inventory):
130
+ for field in ("Device_ID", "Hostname", "Management_IP", "Device_Type", "Vendor",
131
+ "Model", "Serial", "Software_Version", "Site"):
132
+ if not d[field]:
133
+ add(i, "DATA_QUALITY", f"Missing {field}", "MEDIUM", "", "Verify NetBrain device attributes")
134
+ if d["Management_IP"]:
135
+ try:
136
+ ipaddress.ip_address(d["Management_IP"])
137
+ except ValueError:
138
+ add(i, "DATA_QUALITY", "Invalid management IP", "HIGH", d["Management_IP"], "Review management address")
139
+ if d["Site"] and d["Site"].replace("/", chr(92)).split(chr(92))[-1].strip().casefold() == "unassigned":
140
+ add(i, "DATA_QUALITY", "Unassigned site", "MEDIUM", d["Site"], "Review site assignment")
141
+ if d["Discovery_Status"] == "STALE":
142
+ add(i, "DISCOVERY", "Stale discovery", "HIGH", d["Age_Days"], "Review discovery and reachability")
143
+ elif d["Discovery_Status"] == "UNKNOWN":
144
+ add(i, "DISCOVERY", "Unknown discovery age", "MEDIUM", d["Last_Discovery"], "Verify discovery timestamp")
145
+ allowed = None
146
+ for prefix in sorted(policy or {}, key=len, reverse=True):
147
+ if d["Model"].casefold().startswith(prefix.casefold()):
148
+ allowed = policy[prefix]
149
+ break
150
+ status = "NOT_EVALUATED" if policy is None else ("UNKNOWN_MODEL" if allowed is None else
151
+ ("UNKNOWN_VERSION" if not d["Software_Version"] else
152
+ ("PASS" if d["Software_Version"] in allowed else "FAIL")))
153
+ if status == "FAIL":
154
+ add(i, "SOFTWARE", "Unapproved version", "HIGH", d["Software_Version"], "Review approved software policy")
155
+ software.append({k: d[k] for k in ["Device_ID", "Hostname", "Management_IP", "Vendor", "Model", "Software_Version"]} |
156
+ {"Approved_Versions": "; ".join(allowed or []), "Status": status})
157
+
158
+ for field in ("Management_IP", "Hostname", "Serial"):
159
+ groups = defaultdict(list)
160
+ for i, d in enumerate(inventory):
161
+ if d[field]:
162
+ groups[str(d[field]).casefold()].append(i)
163
+ for group in groups.values():
164
+ if len(group) < 2:
165
+ continue
166
+ for i in group:
167
+ d = inventory[i]
168
+ duplicates.append(dict(zip(DUP_FIELDS, [field, d[field], len(group), d["Device_ID"],
169
+ d["Hostname"], d["Management_IP"]])))
170
+ add(i, "DUPLICATE", f"Possible duplicate {field}", "HIGH", d[field], "Validate unique device identity")
171
+ for i in flagged:
172
+ inventory[i]["Audit_Status"] = "REVIEW"
173
+ return inventory, findings, duplicates, software
174
+
175
+
176
+ def version_summary(inventory):
177
+ counts = Counter((d["Vendor"], d["Model"], d["Software_Version"]) for d in inventory)
178
+ return [dict(zip(["Vendor", "Model", "Software_Version", "Devices"], (*key, count)))
179
+ for key, count in sorted(counts.items())]
@@ -0,0 +1,289 @@
1
+ """Command-line interface and report generation."""
2
+ import argparse
3
+ import csv
4
+ import getpass
5
+ import json
6
+ import logging
7
+ import os
8
+ import platform
9
+ import sys
10
+ import tempfile
11
+ import time
12
+ from collections import Counter
13
+ from pathlib import Path
14
+ from rich.console import Console
15
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
16
+ import yaml
17
+ from . import __version__
18
+ from .client import NetBrain, AuditError, APIError, AuthenticationError, ConnectivityError, ci_get
19
+ from .audit import audit, collect, FIELDS, FINDING_FIELDS, DUP_FIELDS, version_summary
20
+
21
+ LOG = logging.getLogger("netbrain_auditor")
22
+ CONSOLE = Console(markup=False)
23
+ SOFTWARE_FIELDS = ["Device_ID", "Hostname", "Management_IP", "Vendor", "Model",
24
+ "Software_Version", "Approved_Versions", "Status"]
25
+
26
+
27
+ def parse_args(argv=None):
28
+ p = argparse.ArgumentParser(description="Read-only NetBrain inventory and data quality audit.",
29
+ formatter_class=argparse.RawDescriptionHelpFormatter,
30
+ epilog="""Examples:
31
+ netbrain-auditor --url https://netbrain.example.local -u USERNAME -o Network_Audit
32
+ netbrain-auditor --url https://netbrain.example.local -u USERNAME --tenant LAB-TENANT --domain LAB-DOMAIN -o Reports
33
+ netbrain-auditor --from-json examples/devices.json -o Demo
34
+ netbrain-auditor --from-json examples/devices.json --software-policy examples/approved_versions.yaml -o Demo
35
+ netbrain-auditor --stale-days 60 -o Reports --overwrite
36
+ netbrain-auditor --help
37
+ """)
38
+ p.add_argument("--version", action="version", version=f"Netbrain_Auditor {__version__}")
39
+ p.add_argument("--url", help="HTTPS NetBrain base URL; prompted if omitted")
40
+ p.add_argument("-u", "--user", "--username", help="Username; prompted if omitted")
41
+ p.add_argument("-p", "--password", "--pasword", help="Password (prefer secure prompt; CLI arguments may be exposed)")
42
+ p.add_argument("--auth-id")
43
+ p.add_argument("--tenant", help="Tenant name or ID")
44
+ p.add_argument("--domain", help="Domain name or ID")
45
+ tls = p.add_mutually_exclusive_group()
46
+ tls.add_argument("--insecure", action="store_true", help="Disable TLS verification; unsafe outside trusted labs")
47
+ tls.add_argument("--ca-file", help="Trusted CA certificate bundle")
48
+ p.add_argument("-o", "--output", help="Report directory; prompted if omitted")
49
+ p.add_argument("--overwrite", action="store_true", help="Replace generated reports in an existing directory")
50
+ p.add_argument("--from-json", help="Audit a local device list or API response without connecting")
51
+ p.add_argument("--raw-json", action="store_true", help="Save collected inventory as Raw_Inventory.json (sensitive)")
52
+ p.add_argument("--stale-days", type=int, default=30, help="Discovery age threshold in days (default: 30)")
53
+ p.add_argument("--software-policy", help="YAML file with approved_versions mapping")
54
+ p.add_argument("--page-size", type=int, choices=range(10, 101), metavar="10-100", default=100)
55
+ p.add_argument("--timeout", type=int, default=30)
56
+ p.add_argument("--retries", type=int, default=3)
57
+ p.add_argument("--retry-backoff", type=float, default=1.0)
58
+ p.add_argument("-v", "--verbose", action="store_true", help="Additional diagnostics in log")
59
+ a = p.parse_args(argv)
60
+ if a.stale_days < 1 or a.timeout < 1 or not 0 <= a.retries <= 10 or not 0 <= a.retry_backoff <= 60:
61
+ p.error("Invalid stale-days, timeout, retries (0-10), or backoff (0-60)")
62
+ if a.from_json and any([a.url, a.user, a.password, a.tenant, a.domain, a.auth_id, a.insecure, a.ca_file]):
63
+ p.error("--from-json cannot be combined with live connection options")
64
+ return a
65
+
66
+
67
+ def choose(items, wanted, name, ident, label):
68
+ if not items:
69
+ raise APIError(f"No accessible {label}s")
70
+ if wanted:
71
+ matches = [x for x in items if str(wanted).casefold() in
72
+ {str(ci_get(x, name)).casefold(), str(ci_get(x, ident)).casefold()}]
73
+ if len(matches) != 1:
74
+ raise AuditError(f"Requested {label} not found or ambiguous")
75
+ return matches[0]
76
+ if len(items) == 1:
77
+ return items[0]
78
+ if not sys.stdin.isatty():
79
+ raise AuditError(f"Specify --{label} for non-interactive operation")
80
+ for i, item in enumerate(items, 1):
81
+ CONSOLE.print(f" {i}. {ci_get(item, name)}")
82
+ try:
83
+ index = int(input(f"Select {label}: "))
84
+ except ValueError:
85
+ raise AuditError(f"Invalid {label} selection") from None
86
+ if not 1 <= index <= len(items):
87
+ raise AuditError(f"Invalid {label} selection")
88
+ return items[index - 1]
89
+
90
+
91
+ def load_policy(path):
92
+ if not path:
93
+ return None
94
+ obj = yaml.safe_load(Path(path).read_text(encoding="utf-8-sig"))
95
+ rules = obj.get("approved_versions") if isinstance(obj, dict) else None
96
+ if not isinstance(rules, dict) or not rules:
97
+ raise AuditError("Policy must contain a nonempty approved_versions mapping")
98
+ seen = set()
99
+ for k, v in rules.items():
100
+ if (not isinstance(k, str) or not k.strip() or k.casefold() in seen or
101
+ not isinstance(v, list) or not v or any(not isinstance(x, str) or not x.strip() for x in v)):
102
+ raise AuditError("Policy requires unique model prefixes and nonempty lists of quoted version strings")
103
+ seen.add(k.casefold())
104
+ return rules
105
+
106
+
107
+ def load_snapshot(path):
108
+ obj = json.loads(Path(path).read_text(encoding="utf-8-sig"))
109
+ if isinstance(obj, dict):
110
+ code = ci_get(obj, "statusCode")
111
+ if code is not None and str(code) not in ("790200", "200", "0"):
112
+ raise APIError("Snapshot contains an API error")
113
+ obj = ci_get(obj, "devices")
114
+ if not isinstance(obj, list) or any(not isinstance(x, dict) for x in obj):
115
+ raise AuditError("Snapshot must contain a device list")
116
+ return obj
117
+
118
+
119
+ def safe_cell(v):
120
+ # Prevent spreadsheet formula injection from untrusted device attributes.
121
+ if isinstance(v, str) and v.lstrip().startswith(("=", "+", "-", "@")):
122
+ return "'" + v
123
+ return v
124
+
125
+
126
+ def atomic_write(path, write):
127
+ fd, name = tempfile.mkstemp(dir=path.parent, prefix=".audit-", suffix=".tmp")
128
+ try:
129
+ with os.fdopen(fd, "w", encoding="utf-8-sig", newline="") as f:
130
+ write(f)
131
+ os.replace(name, path)
132
+ finally:
133
+ if os.path.exists(name):
134
+ os.unlink(name)
135
+
136
+
137
+ def write_csv(path, fields, rows):
138
+ def write(f):
139
+ w = csv.DictWriter(f, fieldnames=fields)
140
+ w.writeheader()
141
+ for row in rows:
142
+ w.writerow({k: safe_cell(row.get(k, "")) for k in fields})
143
+ atomic_write(path, write)
144
+
145
+
146
+ def report(out, records, coverage, scope, policy, stale_days, raw):
147
+ inventory, findings, duplicates, software = audit(records, stale_days, policy)
148
+ summary = {
149
+ "Scope": scope, "Coverage": coverage, "Total devices": len(inventory),
150
+ "Devices with findings": sum(d["Audit_Status"] == "REVIEW" for d in inventory),
151
+ "Devices without findings": sum(d["Audit_Status"] == "PASS" for d in inventory),
152
+ "Findings": len(findings),
153
+ "Stale devices": sum(d["Discovery_Status"] == "STALE" for d in inventory),
154
+ "Unknown discovery age": sum(d["Discovery_Status"] == "UNKNOWN" for d in inventory),
155
+ "Software exceptions": sum(d["Status"] == "FAIL" for d in software),
156
+ "Software policy": "ENABLED" if policy is not None else "NOT_EVALUATED",
157
+ "Duplicate groups": len({(d["Type"], str(d["Value"]).casefold()) for d in duplicates}),
158
+ "Stale threshold days": stale_days,
159
+ }
160
+ for key, count in sorted(Counter(d["Device_Type"] or "UNKNOWN" for d in inventory).items()):
161
+ summary["Device type: " + key] = count
162
+ for key, count in sorted(Counter(d["Severity"] for d in findings).items()):
163
+ summary["Severity: " + key] = count
164
+ for key, count in sorted(Counter(d["Status"] for d in software).items()):
165
+ summary["Software status: " + key] = count
166
+ outputs = [
167
+ ("Network_Inventory.csv", FIELDS, inventory),
168
+ ("Audit_Findings.csv", FINDING_FIELDS, findings),
169
+ ("Software_Versions.csv", SOFTWARE_FIELDS, software),
170
+ ("Software_Summary.csv", ["Vendor", "Model", "Software_Version", "Devices"], version_summary(inventory)),
171
+ ("Stale_Devices.csv", FIELDS, [d for d in inventory if d["Discovery_Status"] == "STALE"]),
172
+ ("Missing_Information.csv", FINDING_FIELDS, [d for d in findings if d["Category"] == "DATA_QUALITY" or d["Finding"] == "Unknown discovery age"]),
173
+ ("Duplicate_Devices.csv", DUP_FIELDS, duplicates),
174
+ ("Audit_Summary.csv", ["Metric", "Value"], [{"Metric": k, "Value": v} for k, v in summary.items()]),
175
+ ]
176
+ for name, fields, rows in outputs:
177
+ write_csv(out / name, fields, rows)
178
+ LOG.info("Report %s: %s rows", name, len(rows))
179
+ if raw:
180
+ atomic_write(out / "Raw_Inventory.json", lambda f: json.dump(records, f, indent=2, ensure_ascii=False))
181
+ LOG.warning("Raw inventory contains network data")
182
+ return summary
183
+
184
+
185
+ def main(argv=None):
186
+ a = parse_args(argv)
187
+ start = time.monotonic()
188
+ client = None
189
+ handler = None
190
+ log_path = None
191
+ try:
192
+ out = Path(a.output or input("Output directory [Network_Audit]: ").strip() or "Network_Audit").expanduser()
193
+ out.mkdir(parents=True, exist_ok=True)
194
+ if not a.overwrite and any(out.iterdir()):
195
+ raise AuditError("Output directory is not empty. Choose another -o or use --overwrite.")
196
+ names = ["Network_Inventory.csv", "Audit_Findings.csv", "Software_Versions.csv",
197
+ "Software_Summary.csv", "Stale_Devices.csv", "Missing_Information.csv",
198
+ "Duplicate_Devices.csv", "Audit_Summary.csv", "Network_Audit.log", "Raw_Inventory.json"]
199
+ # Never overwrite source or policy, even when --overwrite is requested.
200
+ for source in (a.from_json, a.software_policy, a.ca_file):
201
+ if source and any(Path(source).resolve() == (out / n).resolve() for n in names):
202
+ raise AuditError("Input file conflicts with a generated output")
203
+ log_path = out / "Network_Audit.log"
204
+ handler = logging.FileHandler(log_path, mode="w" if a.overwrite else "x", encoding="utf-8")
205
+ handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
206
+ LOG.addHandler(handler)
207
+ LOG.setLevel(logging.DEBUG if a.verbose else logging.INFO)
208
+ LOG.info("Version=%s Python=%s Platform=%s mode=%s", __version__, platform.python_version(),
209
+ platform.system(), "OFFLINE" if a.from_json else "LIVE")
210
+ LOG.info("Timeout=%s retries=%s backoff=%s stale_days=%s page_size=%s TLS verify=%s",
211
+ a.timeout, a.retries, a.retry_backoff, a.stale_days, a.page_size, not a.insecure)
212
+ policy = load_policy(a.software_policy)
213
+ CONSOLE.print("=" * 68, style="green")
214
+ CONSOLE.print("NETBRAIN NETWORK AUDITOR".center(68), style="green")
215
+ CONSOLE.print("=" * 68, style="green")
216
+ if a.from_json:
217
+ CONSOLE.print("[+] Loading offline inventory...", style="green")
218
+ records = load_snapshot(a.from_json)
219
+ coverage, scope = "OFFLINE_UNVERIFIED", "OFFLINE_SNAPSHOT"
220
+ else:
221
+ url = (a.url or input("NetBrain URL: ")).strip()
222
+ user = a.user or input("NetBrain Username: ").strip()
223
+ password = a.password if a.password is not None else getpass.getpass("NetBrain Password: ")
224
+ a.password = None
225
+ if not user or not password:
226
+ raise AuthenticationError("Username and password are required")
227
+ client = NetBrain(url, user, password, auth_id=a.auth_id, insecure=a.insecure,
228
+ ca_file=a.ca_file, timeout=a.timeout, retries=a.retries, backoff=a.retry_backoff)
229
+ del password
230
+ CONSOLE.print("[+] Validating NetBrain connectivity...", style="green")
231
+ CONSOLE.print(f" URL : {url}")
232
+ client.validate_connection()
233
+ CONSOLE.print(" Status : Reachable", style="green")
234
+ CONSOLE.print("[+] Connecting to NetBrain API...", style="green")
235
+ client.login()
236
+ CONSOLE.print(" Login : Successful", style="green")
237
+ CONSOLE.print(" Token : Received", style="green")
238
+ scope = client.select_domain(a.tenant, a.domain, choose)
239
+ CONSOLE.print(f" Domain : {scope}", style="green")
240
+ LOG.info("Selected domain: %s", scope)
241
+ CONSOLE.print("[+] Collecting network inventory...", style="green")
242
+ with Progress(SpinnerColumn(), TextColumn("{task.description}"), BarColumn(),
243
+ TaskProgressColumn(), console=CONSOLE) as progress:
244
+ task = progress.add_task("Devices: 0", total=None)
245
+ def update(count, total):
246
+ progress.update(task, description=f"Devices: {count}", completed=count, total=total)
247
+ records, coverage = collect(client, a.page_size, update)
248
+ progress.update(task, total=max(1, len(records)), completed=max(1, len(records)))
249
+ CONSOLE.print("[+] Running inventory audit...", style="green")
250
+ summary = report(out, records, coverage, scope, policy, a.stale_days, a.raw_json)
251
+ CONSOLE.print("=" * 68, style="green")
252
+ CONSOLE.print("SUMMARY".center(68), style="green")
253
+ CONSOLE.print("=" * 68, style="green")
254
+ for k in ["Total devices", "Devices without findings", "Devices with findings", "Findings",
255
+ "Stale devices", "Unknown discovery age", "Duplicate groups", "Software exceptions",
256
+ "Software policy", "Coverage"]:
257
+ CONSOLE.print(f" {k:25}: {summary[k]}")
258
+ CONSOLE.print(f" {'Report directory':25}: {out}")
259
+ CONSOLE.print(f" {'Diagnostic log':25}: {log_path}")
260
+ CONSOLE.print(f" {'Execution time':25}: {time.monotonic()-start:.2f}s")
261
+ CONSOLE.print("[+] Audit completed successfully.", style="green")
262
+ return 0
263
+ except KeyboardInterrupt:
264
+ LOG.warning("Cancelled")
265
+ CONSOLE.print("[-] Cancelled by user.", style="yellow")
266
+ return 130
267
+ except (AuthenticationError, ConnectivityError, AuditError, OSError, ValueError, yaml.YAMLError, EOFError) as exc:
268
+ LOG.error("%s: %s", type(exc).__name__, exc)
269
+ message = ("NetBrain authentication failed." if isinstance(exc, AuthenticationError) else
270
+ "Unable to reach NetBrain server." if isinstance(exc, ConnectivityError) else
271
+ "NetBrain API or inventory validation failed." if isinstance(exc, APIError) else
272
+ str(exc) if isinstance(exc, AuditError) else "Input or file operation failed.")
273
+ CONSOLE.print(f"[-] ERROR: {message}", style="red")
274
+ if log_path and handler:
275
+ CONSOLE.print(f" Diagnostic log: {log_path}")
276
+ return 3 if isinstance(exc, AuthenticationError) else 4 if isinstance(exc, ConnectivityError) else 5 if isinstance(exc, APIError) else 2
277
+ except Exception as exc:
278
+ LOG.error("Unexpected error type: %s", type(exc).__name__)
279
+ CONSOLE.print(f"[-] ERROR: Unexpected {type(exc).__name__}.", style="red")
280
+ if log_path and handler:
281
+ CONSOLE.print(f" Diagnostic log: {log_path}")
282
+ return 1
283
+ finally:
284
+ if client:
285
+ client.close()
286
+ if handler:
287
+ LOG.info("Execution time: %.2fs", time.monotonic()-start)
288
+ LOG.removeHandler(handler)
289
+ handler.close()
@@ -0,0 +1,190 @@
1
+ """NetBrain REST client, based on the Lookup 2.6.4 RC4 session design."""
2
+ import json
3
+ import logging
4
+ import ssl
5
+ import time
6
+ from urllib.error import HTTPError, URLError
7
+ from urllib.parse import urlencode, urlsplit
8
+ from urllib.request import Request, build_opener, HTTPSHandler, HTTPRedirectHandler
9
+
10
+ LOG = logging.getLogger("netbrain_auditor")
11
+ BASE = "/ServicesAPI/API/V1"
12
+ SESSION = BASE + "/Session"
13
+ DEVICES = BASE + "/CMDB/Devices"
14
+ DOMAIN = SESSION + "/CurrentDomain"
15
+
16
+
17
+ class AuditError(Exception):
18
+ """An expected audit failure."""
19
+
20
+
21
+ class AuthenticationError(AuditError):
22
+ pass
23
+
24
+
25
+ class ConnectivityError(AuditError):
26
+ pass
27
+
28
+
29
+ class APIError(AuditError):
30
+ pass
31
+
32
+
33
+ class NoRedirect(HTTPRedirectHandler):
34
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
35
+ return None
36
+
37
+
38
+ def ci_get(obj, key, default=None):
39
+ return next((v for k, v in obj.items() if k.casefold() == key.casefold()), default)
40
+
41
+
42
+ def require_list(obj, key):
43
+ value = ci_get(obj, key)
44
+ if not isinstance(value, list) or any(not isinstance(x, dict) for x in value):
45
+ raise APIError(f"Invalid or missing {key} array")
46
+ return value
47
+
48
+
49
+ class NetBrain:
50
+ def __init__(self, url, user, password, *, auth_id=None, insecure=False,
51
+ ca_file=None, timeout=30, retries=3, backoff=1.0):
52
+ p = urlsplit(url)
53
+ if p.scheme != "https" or not p.hostname or p.username or p.password or p.query or p.fragment:
54
+ raise AuditError("Use an HTTPS NetBrain base URL without credentials or query parameters.")
55
+ self.url = url.rstrip("/")
56
+ self.user = user
57
+ self._password = password
58
+ self.auth_id = auth_id
59
+ self.timeout = timeout
60
+ self.retries = retries
61
+ self.backoff = backoff
62
+ self.token = None
63
+ self.renewed = False
64
+ self.domain = None
65
+ ctx = ssl._create_unverified_context() if insecure else ssl.create_default_context(cafile=ca_file)
66
+ self.opener = build_opener(HTTPSHandler(context=ctx), NoRedirect())
67
+ if insecure:
68
+ LOG.warning("TLS certificate verification disabled")
69
+
70
+ def _request(self, method, path, params=None, body=None, auth=True, probe=False):
71
+ url = self.url + path
72
+ if params:
73
+ url += "?" + urlencode(params)
74
+ data = json.dumps(body).encode() if body is not None else None
75
+ for attempt in range(self.retries + 1):
76
+ headers = {"Content-Type": "application/json", "Accept": "application/json"}
77
+ if auth and self.token:
78
+ headers["Token"] = self.token
79
+ req = Request(url, data=data, headers=headers, method=method)
80
+ retry_after = None
81
+ try:
82
+ with self.opener.open(req, timeout=self.timeout) as res:
83
+ status = res.status
84
+ payload = res.read()
85
+ except HTTPError as exc:
86
+ status = exc.code
87
+ retry_after = exc.headers.get("Retry-After")
88
+ exc.close()
89
+ payload = b""
90
+ except (URLError, TimeoutError, OSError) as exc:
91
+ reason = getattr(exc, "reason", exc)
92
+ if isinstance(reason, ssl.SSLError):
93
+ raise ConnectivityError("TLS verification or handshake failed") from None
94
+ if isinstance(reason, TimeoutError) and attempt < self.retries:
95
+ self._delay(attempt, None, path, "timeout")
96
+ continue
97
+ raise ConnectivityError(f"Network request failed at {path}: {type(reason).__name__}") from None
98
+ LOG.debug("%s %s HTTP %s", method, path, status)
99
+ if status == 429 or 500 <= status < 600:
100
+ if attempt < self.retries:
101
+ self._delay(attempt, retry_after, path, status)
102
+ continue
103
+ if probe:
104
+ return status
105
+ if auth and status == 401:
106
+ if self.renewed:
107
+ raise AuthenticationError("Session rejected after one renewal")
108
+ self.renewed = True
109
+ LOG.warning("Session rejected; renewing once")
110
+ self.login()
111
+ if self.domain:
112
+ self._request("PUT", DOMAIN, body=self.domain)
113
+ # Reissue once with a fresh retry budget; renewed guards recursion.
114
+ return self._request(method, path, params=params, body=body, auth=auth)
115
+ if not auth and status in (400, 401, 403):
116
+ raise AuthenticationError(f"Authentication rejected (HTTP {status})")
117
+ if not 200 <= status < 300:
118
+ raise APIError(f"{method} {path} failed: HTTP {status}")
119
+ if method == "DELETE" and not payload:
120
+ return {}
121
+ try:
122
+ obj = json.loads(payload)
123
+ except (ValueError, UnicodeError):
124
+ raise APIError(f"Invalid JSON from {path}") from None
125
+ if not isinstance(obj, dict):
126
+ raise APIError(f"Invalid response object from {path}")
127
+ code = ci_get(obj, "statusCode")
128
+ if str(code) not in ("790200", "200", "0"):
129
+ error_type = AuthenticationError if not auth else APIError
130
+ raise error_type(f"{path}: unexpected NetBrain statusCode {code!r}")
131
+ return obj
132
+ raise APIError("Retry budget exhausted")
133
+
134
+ def _delay(self, attempt, retry_after, path, reason):
135
+ delay = min(30.0, self.backoff * 2 ** min(attempt, 20))
136
+ if retry_after:
137
+ try:
138
+ delay = max(0.0, min(float(retry_after), 120.0))
139
+ except ValueError:
140
+ pass
141
+ LOG.warning("Retry %d/%d: %s (%s), wait %.1fs", attempt + 1, self.retries, path, reason, delay)
142
+ time.sleep(delay)
143
+
144
+ def validate_connection(self):
145
+ status = self._request("GET", SESSION, auth=False, probe=True)
146
+ if status >= 500 or status == 429 or 300 <= status < 400:
147
+ raise ConnectivityError(f"Connectivity probe returned HTTP {status}")
148
+ LOG.info("Connectivity probe HTTP %s", status)
149
+
150
+ def login(self):
151
+ body = {"username": self.user, "password": self._password}
152
+ if self.auth_id:
153
+ body["authentication_id"] = self.auth_id
154
+ try:
155
+ obj = self._request("POST", SESSION, body=body, auth=False)
156
+ finally:
157
+ body.clear()
158
+ token = ci_get(obj, "token")
159
+ if not isinstance(token, str) or not token:
160
+ raise AuthenticationError("Authentication response had no token")
161
+ self.token = token
162
+ LOG.info("Authentication successful")
163
+
164
+ def select_domain(self, tenant, domain, choose):
165
+ tenants = require_list(self._request("GET", BASE + "/CMDB/Tenants"), "tenants")
166
+ t = choose(tenants, tenant, "tenantName", "tenantId", "tenant")
167
+ tid = ci_get(t, "tenantId")
168
+ domains = require_list(self._request("GET", BASE + "/CMDB/Domains", {"tenantId": tid}), "domains")
169
+ d = choose(domains, domain, "domainName", "domainId", "domain")
170
+ payload = {"tenantId": tid, "domainId": ci_get(d, "domainId")}
171
+ if not all(payload.values()):
172
+ raise APIError("Tenant or domain ID missing")
173
+ self._request("PUT", DOMAIN, body=payload)
174
+ self.domain = payload
175
+ return f"{ci_get(t, 'tenantName')} / {ci_get(d, 'domainName')}"
176
+
177
+ def device_page(self, skip, limit):
178
+ return self._request("GET", DEVICES, {"fullattr": 1, "version": 1, "skip": skip, "limit": limit})
179
+
180
+ def close(self):
181
+ try:
182
+ if self.token:
183
+ # Do not renew a token during logout.
184
+ self.renewed = True
185
+ self._request("DELETE", SESSION)
186
+ except AuditError as exc:
187
+ LOG.warning("Session cleanup: %s", exc)
188
+ finally:
189
+ self.token = None
190
+ self._password = None
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: netbrain-auditor
3
+ Version: 1.0.0
4
+ Summary: Read-only NetBrain inventory and data quality auditor
5
+ Author: Peskicorp
6
+ Project-URL: Repository, https://github.com/jpesqueda/Netbrain_Auditor
7
+ Project-URL: Issues, https://github.com/jpesqueda/Netbrain_Auditor/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: System :: Networking
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: rich>=13
14
+ Requires-Dist: PyYAML>=6
15
+
16
+ # Netbrain Auditor
17
+
18
+ Read-only network inventory and data-quality audit for NetBrain. Version 1.0.0.
19
+
20
+ ## English
21
+
22
+ Install after publication: `pip install netbrain-auditor`.
23
+
24
+ Run: `netbrain-auditor --url https://netbrain.example.local -u USERNAME --tenant LAB-TENANT --domain LAB-DOMAIN -o Network_Audit`.
25
+
26
+ Use `netbrain-auditor --help` for options. Password is prompted without echo. TLS verification is enabled by default. Reports reflect the selected domain and account permissions, not live device state.
27
+
28
+ ## Español
29
+
30
+ Auditoría de inventario, antigüedad de descubrimiento, datos faltantes, duplicados y versiones. No modifica dispositivos ni inicia tareas de discovery. Los hallazgos son candidatos a revisión, no prueba de fallas físicas.
31
+
32
+ Ejemplo: `netbrain-auditor --url https://netbrain.example.local -u USERNAME -o Network_Audit`.
33
+
34
+ Modo sin conexión: `netbrain-auditor --from-json examples/devices.json -o Demo`.
35
+
36
+ Política opcional: `--software-policy examples/approved_versions.yaml`. Sin política, las versiones se inventarían sin emitir un veredicto de cumplimiento. Prefijos de modelos se comparan sin distinguir mayúsculas, con el prefijo más largo primero; versiones exactas.
37
+
38
+ ## Reports / Reportes
39
+
40
+ - Network_Inventory.csv: normalized inventory
41
+ - Audit_Findings.csv: one row per finding
42
+ - Software_Versions.csv: per-device version and compliance
43
+ - Software_Summary.csv: counts by vendor, model and version
44
+ - Stale_Devices.csv: devices older than the threshold
45
+ - Missing_Information.csv: missing or unusable fields, unassigned sites
46
+ - Duplicate_Devices.csv: possible duplicate management IP, hostname, serial
47
+ - Audit_Summary.csv: coverage and counts
48
+ - Network_Audit.log: diagnostics and elapsed time
49
+
50
+ Default stale threshold: 30 days. Unknown discovery times remain unknown. Reports may contain sensitive infrastructure data; do not commit or share them without sanitization. Existing output directories must be empty unless --overwrite is explicitly supplied. Successful collection is scoped to the account's visible inventory. No automatic publication until a maintainer configures trusted publishing.
51
+
52
+ ## Development
53
+
54
+ ```sh
55
+ python -m pip install -e .
56
+ python -m unittest discover -s tests
57
+ python -m pip install build twine
58
+ python -m build
59
+ python -m twine check dist/*
60
+ ```
61
+
62
+ See PUBLISHING.md for TestPyPI and PyPI steps. All example data is synthetic.
@@ -0,0 +1,10 @@
1
+ netbrain_auditor/__init__.py,sha256=jXKCp0gHE9d9B3OZoq_WBi2rXxhC--IVdNgTy69Brqc,67
2
+ netbrain_auditor/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ netbrain_auditor/audit.py,sha256=FTLmvddIMtpE04vqn3778VbsQjVgQNwE1HGSq-ZzyB4,8477
4
+ netbrain_auditor/cli.py,sha256=I7cwR1p0edoGpGipIi8oUMHQefiLTEm3TraajJA2QBw,15592
5
+ netbrain_auditor/client.py,sha256=LIm0IoI4g16-2gkiNiOwry_2-xB9StB-pbXn8q_r_TM,7926
6
+ netbrain_auditor-1.0.0.dist-info/METADATA,sha256=b7aByezr8pGLPKHiwUPWiYZb-W0gKF317EOusYG9iQo,2914
7
+ netbrain_auditor-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ netbrain_auditor-1.0.0.dist-info/entry_points.txt,sha256=_t0gYDh6HlMemu5aHNB1vu0ffZckEyL2MogbUXuKtdk,107
9
+ netbrain_auditor-1.0.0.dist-info/top_level.txt,sha256=OURozH0AVmzYBO_AaQLgYkP5BBbpNWIQu9vfTA_qpeM,17
10
+ netbrain_auditor-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ netbrain-auditor = netbrain_auditor.cli:main
3
+ netbrainauditor = netbrain_auditor.cli:main
@@ -0,0 +1 @@
1
+ netbrain_auditor