nadzoring.utils.formatters module¶
Output formatting utilities for CLI commands.
- type nadzoring.utils.formatters.OutputFormat = Literal['table', 'json', 'csv', 'html', 'html_table']¶
Valid output format types for CLI commands.
- type nadzoring.utils.formatters.RecordData = dict[str, Any]¶
Type alias for DNS record data structures.
- nadzoring.utils.formatters._build_html_page(title: str, html_table: str) str[source]¶
Wrap an HTML table fragment in a complete, styled HTML page.
- Parameters:
title – Page
<title>and<h1>heading text.html_table – Raw HTML
<table>string to embed.
- Returns:
Complete HTML document as a string.
- nadzoring.utils.formatters._calculate_column_widths(headers: list[str], min_widths: dict[str, int], max_widths: dict[str, int], available: int) list[int][source]¶
Distribute available width across columns, respecting per-column limits.
Extra space beyond the minimum widths is divided equally; the result is clamped to each column’s maximum. If the total still exceeds available, the widest columns are trimmed first.
- Parameters:
headers – Column header names (defines ordering).
min_widths – Minimum character width per column.
max_widths – Maximum character width per column.
available – Total character budget for all columns combined.
- Returns:
List of integer column widths in the same order as headers.
- nadzoring.utils.formatters._format_scan_results(results: list[ScanResult], *, show_closed: bool) list[dict[str, Any]][source]¶
Convert
ScanResultobjects into CLI-displayable dicts.- Parameters:
results – Port scan results to format.
show_closed – When
True, closed/filtered ports are included alongside open ones.
- Returns:
List of flat dicts with
target,ip,port,state,service,banner, andresponse_time_mskeys.
- nadzoring.utils.formatters.colorize_value(value: Any, *, no_color: bool = False) str[source]¶
Apply ANSI colour formatting to a value based on its semantic meaning.
Colours are chosen by matching the uppercased string against severity keyword sets:
Red/bold — critical/error terms (
CRITICAL,HIGH, …)Yellow/bold — warning terms (
MEDIUM,WARNING, …)Green — informational/positive terms (
LOW,yes,up, …)
- Parameters:
value – Value to format. Converted to
strbefore matching.no_color – When
Truecolours are disabled and the plain string is returned. Defaults toFalse.
- Returns:
ANSI-coloured string, or a plain string when no_color is
Trueor the value does not match any keyword set.
Examples
>>> colorize_value("CRITICAL") '\x1b[1;31mCRITICAL\x1b[0m'
- nadzoring.utils.formatters.format_dns_comparison(comparison_result: dict[str, Any]) list[dict[str, Any]][source]¶
Format DNS comparison results for tabular display.
- Parameters:
comparison_result – Dict with a
serverskey mapping server names to per-type response data.- Returns:
List of dicts with
server,type,response_time_ms,records, anddifferscolumns.
Examples
>>> comp = {"servers": {"8.8.8.8": {"A": {"records": ["1.2.3.4"]}}}} >>> format_dns_comparison(comp)[0]["server"] '8.8.8.8'
- nadzoring.utils.formatters.format_dns_health(health_result: dict[str, Any]) list[dict[str, Any]][source]¶
Format DNS health check results for tabular display.
- Parameters:
health_result – Dict with
domain,score,status,issues,warnings, andrecord_scoreskeys.- Returns:
one summary row followed by per-record-type rows.
- Return type:
List of dicts
Examples
>>> health = { ... "domain": "example.com", ... "score": 85, ... "status": "healthy", ... "issues": [], ... "warnings": [], ... "record_scores": {}, ... } >>> format_dns_health(health)[0]["overall_score"] '85/100'
- nadzoring.utils.formatters.format_dns_poisoning(poisoning_result: dict[str, Any]) list[dict[str, Any]][source]¶
Build a detailed, human-readable breakdown of a DNS poisoning check.
The result is organised into logical sections (DNS ANALYSIS, CONTROL SERVER, SUMMARY, CDN DETECTION, IP DIVERSITY, CONSENSUS, ANALYSIS, DETAILS, VERDICT) and returned as a flat list of rows suitable for table rendering.
- Parameters:
poisoning_result – Poisoning check result dict as returned by
nadzoring.dns_lookup.check_dns_poisoning().- Returns:
List of dicts with
section,detail,value, andnotecolumns.
Examples
>>> result = { ... "domain": "example.com", ... "poisoning_level": "NONE", ... "confidence": 100, ... "cdn_detected": False, ... "poisoned": False, ... } >>> format_dns_poisoning(result)[-1]["detail"] 'CLEAN'
- nadzoring.utils.formatters.format_dns_record(results: Sequence[dict[str, Any]], style: str = 'standard', *, show_ttl: bool = False) list[dict[str, Any]][source]¶
Format DNS records into a display-ready list of dicts.
- Parameters:
results – Raw DNS query results. Each item must contain
domainandrecordskeys.style – Output style —
"short"produces one row per record value; any other value produces one row per domain.show_ttl – When
True, TTL values are appended to each record string in standard style. Defaults toFalse.
- Returns:
Formatted records ready for display.
Examples
>>> data = [ ... {"domain": "example.com", "records": {"A": {"records": ["1.2.3.4"]}}} ... ] >>> format_dns_record(data, style="standard") [{'domain': 'example.com', 'A': '1.2.3.4'}] >>> format_dns_record(data, style="short") [{'domain': 'example.com', 'type': 'A', 'value': '1.2.3.4'}]
- nadzoring.utils.formatters.format_dns_trace(trace_result: dict[str, Any]) list[dict[str, Any]][source]¶
Format a DNS trace result for tabular display.
- Parameters:
trace_result – Raw trace dict with
hops(list) and optionalfinal_answerkeys.- Returns:
List of dicts with
hop,nameserver,response_time,records, andnextcolumns.
Examples
>>> trace = {"hops": [{"nameserver": "8.8.8.8", "response_time": 42}]} >>> format_dns_trace(trace)[0]["nameserver"] '8.8.8.8'
- nadzoring.utils.formatters.format_scan_results(results: list[ScanResult], *, show_closed: bool) list[dict[str, Any]][source]¶
Convert
ScanResultobjects into CLI-displayable dicts.Public alias for the internal formatter used by network commands.
- Parameters:
results – Port scan results to format.
show_closed – When
True, closed/filtered ports are included alongside open ones.
- Returns:
List of flat dicts with
target,ip,port,state,service,banner, andresponse_time_mskeys.
- nadzoring.utils.formatters.get_terminal_width() int[source]¶
Return the current terminal width in columns.
Falls back to a sensible default when the terminal size cannot be determined.
- Returns:
Number of columns available in the terminal.
- nadzoring.utils.formatters.print_csv_table(data: Sequence[dict[str, Any]]) None[source]¶
Print data in CSV format to standard output.
- Parameters:
data – Rows to format. All dicts should share the same keys for well-formed CSV output.
Examples
>>> print_csv_table([{"domain": "example.com", "ip": "1.2.3.4"}]) domain,ip example.com,1.2.3.4
- nadzoring.utils.formatters.print_html_table(data: Sequence[dict[str, Any]], *, full_page: bool = False) None[source]¶
Print results as an HTML table or complete HTML page.
- Parameters:
data – Rows to render as an HTML table.
full_page – When
Truea complete HTML document with inline CSS styling is generated. WhenFalseonly the<table>element is printed. Defaults toFalse.
- nadzoring.utils.formatters.print_results_table(data: Sequence[dict[str, Any]], tablefmt: str = 'simple_grid', *, no_color: bool = False) None[source]¶
Print a formatted table that fits the current terminal width.
Column widths are calculated automatically; special DNS record type columns (
TXT,AAAA, etc.) have predefined maximum widths.- Parameters:
data – Rows to display. Each dict must have the same keys.
tablefmt –
tabulateformat string. Defaults to"simple_grid".no_color – Disable colour formatting when
True. Defaults toFalse.
- nadzoring.utils.formatters.save_results(data: Any, filename: str, fileformat: str) None[source]¶
Save command results to a file in the specified format.
Creates parent directories automatically when they do not exist. Errors are reported to stderr via
click.secho()rather than raising exceptions so that the CLI remains user-friendly.- Parameters:
data – Data to persist. Structure depends on fileformat: JSON — any JSON-serialisable object; CSV / HTML — list of dicts with consistent keys.
filename – Destination file path.
fileformat – One of
"json","csv","html","html_table", or any other value (falls back to plaintabulategrid output).
- nadzoring.utils.formatters.truncate_string(s: str, max_width: int, placeholder: str = '...') str[source]¶
Truncate s to fit within max_width characters.
If s is already within the limit it is returned unchanged. Otherwise it is shortened and placeholder is appended to signal truncation.
- Parameters:
s – The string to truncate.
max_width – Maximum allowed length in characters.
placeholder – Suffix appended to truncated strings. Defaults to
"...".
- Returns:
Original string when within limits; truncated string with placeholder otherwise.
Examples
>>> truncate_string("very long string", 10) 'very lo...'