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._calculate_column_widths(headers: list[str], min_widths: dict[str, int], max_widths: dict[str, int], available: int) list[int][source]¶
Calculate optimal column widths within available space.
Distributes extra space proportionally while respecting minimum and maximum constraints for each column.
- Parameters:
headers – List of column header names.
min_widths – Dictionary mapping headers to minimum required widths.
max_widths – Dictionary mapping headers to maximum allowed widths.
available – Total available width for all columns combined.
- Returns:
Calculated width for each column in header order.
- Return type:
list[int]
- nadzoring.utils.formatters._format_scan_results(results: list[ScanResult], *, show_closed: bool) list[dict[str, Any]][source]¶
Format scan results for CLI output.
- nadzoring.utils.formatters.colorize_value(value: Any, *, no_color: bool = False) str[source]¶
Apply color formatting to values based on content and severity.
- Colors are applied based on keywords in the string value:
Red/bold: Critical/high severity terms
Yellow/bold: Medium severity/warning terms
Green: Low severity/positive terms
No color: Other values
- Parameters:
value – The value to colorize.
no_color – If True, disable color formatting (default: False).
- Returns:
Colorized string if colors enabled, otherwise plain string.
- Return type:
str
Example
>>> colorize_value("CRITICAL") '\x1b[1;31mCRITICAL\x1b[0m' # Red bold text
- nadzoring.utils.formatters.format_dns_comparison(comparison_result: dict[str, Any]) list[dict[str, Any]][source]¶
Format DNS server comparison results for display.
Transforms comparison results showing differences between multiple DNS servers into a tabular format.
- Parameters:
comparison_result – Dictionary containing: - servers: Dictionary mapping server names to their response data
- Returns:
- Formatted comparison data with columns:
server: DNS server name/identifier
type: Record type (A, AAAA, MX, etc.)
response_time_ms: Response time in milliseconds
records: Records returned (joined with newlines)
differs: “✓” if record differs from reference, else “ “
- Return type:
list[dict]
Example
>>> comp = {"servers": {"8.8.8.8": {"A": {"records": ["1.2.3.4"]}}}} >>> format_dns_comparison(comp) [{"server": "8.8.8.8", "type": "A", "response_time_ms": "N/A", ...}]
- nadzoring.utils.formatters.format_dns_health(health_result: dict[str, Any]) list[dict[str, Any]][source]¶
Format DNS health check results for tabular display.
Converts health check results showing overall domain health and per-record-type scores into a readable format.
- Parameters:
health_result – Dictionary containing: - domain: Domain name that was checked - score: Overall health score (0-100) - status: Overall status (healthy, warning, critical) - issues: List of detected issues - warnings: List of warnings - record_scores: Dictionary mapping record types to scores
- Returns:
- Formatted health data with:
domain: Domain name (indented for record types)
overall_score: Score as “X/100”
status: Uppercase status
issues: Issues (joined with newlines)
warnings: Warnings (joined with newlines)
- Return type:
list[dict]
Example
>>> health = {"domain": "example.com", "score": 85, "status": "healthy"} >>> format_dns_health(health) [{"domain": "example.com", "overall_score": "85/100", ...}]
- nadzoring.utils.formatters.format_dns_poisoning(poisoning_result: dict[str, Any]) list[dict[str, Any]][source]¶
Format DNS poisoning check results with detailed analysis.
Creates a comprehensive, human-readable breakdown of DNS poisoning test results, including server analysis, CDN detection, and verdict.
- Parameters:
poisoning_result – Dictionary containing poisoning check results with: - domain: Domain that was tested - record_type: DNS record type tested - poisoning_level: Detected poisoning level - confidence: Confidence percentage in detection - cdn_detected: Whether CDN was detected - control_server: Control server used - test_servers_count: Number of servers tested - mismatches: Count of mismatching responses - inconsistencies: List of detected inconsistencies - and many other detailed metrics
- Returns:
- Formatted analysis data with columns:
section: Section header or detail prefix
detail: Primary information
value: Secondary value/metric
note: Additional context or explanation
- Return type:
list[dict]
- The output is organized into logical sections:
DNS ANALYSIS: Basic test info
CONTROL SERVER: Reference server details
SUMMARY: Overall statistics
CDN DETECTION: If CDN detected
VERDICT: Final determination
Example
>>> result = {"domain": "example.com", "poisoning_level": "NONE"} >>> format_dns_poisoning(result) [{"section": "DNS ANALYSIS", "detail": "example.com (A)", ...}]
- nadzoring.utils.formatters.format_dns_record(results: Sequence[dict[str, Any]], style: Literal['standard', 'short'] = 'standard', *, show_ttl: bool = False) list[dict[str, Any]][source]¶
Format DNS records in different display styles.
Transforms raw DNS record data into human-readable formats suitable for different display contexts.
- Parameters:
results – List of DNS query results. Each result should contain: - domain: The queried domain name - records: Dictionary mapping record types to their data
style – Output style: - “standard”: One row per domain with all record types - “short”: One row per individual record (flattened)
show_ttl – If True, include TTL values in record display (default: False).
- Returns:
Formatted records ready for display. Structure depends on style.
- Return type:
list[dict]
- Example (standard style):
>>> 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"}]
- Example (short style):
>>> 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 DNS trace route results for tabular display.
Converts a DNS trace result into a list of dictionaries suitable for table formatting, showing each hop in the resolution path.
- Parameters:
trace_result – Dictionary containing trace results with: - hops: List of intermediate DNS server responses - final_answer: Optional final authoritative response
- Returns:
- Formatted trace data with columns:
hop: Hop number in the trace
nameserver: Server that responded
response_time: Response time in ms or “timeout”
records: DNS records returned (joined with newlines)
next: Next nameserver to query
- Return type:
list[dict]
Example
>>> trace = {"hops": [{"nameserver": "8.8.8.8", "response_time": 42}]} >>> format_dns_trace(trace) [{"hop": 0, "nameserver": "8.8.8.8", "response_time": "42.00ms", ...}]
- nadzoring.utils.formatters.get_terminal_width() int[source]¶
Get the current terminal width in columns.
- Returns:
- Number of columns available in the terminal. Falls back to a
reasonable default if terminal size cannot be determined.
- Return type:
int
- nadzoring.utils.formatters.print_csv_table(data: Sequence[dict[str, Any]]) None[source]¶
Print data as CSV format to console.
- Parameters:
data – List of dictionaries to convert to CSV format. All dictionaries should have the same keys for proper CSV formatting.
- Returns:
CSV data is printed directly to console.
- Return type:
None
Example
>>> data = [{"domain": "example.com", "ip": "192.168.1.1"}] >>> print_csv_table(data) domain,ip example.com,192.168.1.1
- nadzoring.utils.formatters.print_html_table(data: Sequence[dict[str, Any]], *, full_page: bool = False) None[source]¶
Print results as HTML table or complete HTML page.
- Parameters:
data – List of dictionaries containing the results to format.
full_page – If True, generate complete HTML page with styling and timestamp. If False, generate only the HTML table (default: False).
- Returns:
HTML content is printed directly to console.
- Return type:
None
Example
>>> data = [{"domain": "example.com", "status": "OK"}] >>> print_html_table(data) <table>...
- nadzoring.utils.formatters.print_results_table(data: Sequence[dict[str, Any]], tablefmt: str = 'simple_grid', *, no_color: bool = False) None[source]¶
Print results as a formatted table that fits terminal width.
Automatically adjusts column widths based on terminal size and content. Special handling for DNS record types (TXT, AAAA, etc.) with predefined maximum widths.
- Parameters:
data – List of dictionaries containing the results to display.
tablefmt – Tabulate table format string (default: “simple_grid”).
no_color – If True, disable color formatting (default: False).
- Returns:
Results are printed directly to console.
- Return type:
None
Example
>>> data = [{"domain": "example.com", "A": "192.168.1.1"}] >>> print_results_table(data) +-------------+-------------+ | domain | A | +-------------+-------------+ | example.com | 192.168.1.1 | +-------------+-------------+
- nadzoring.utils.formatters.save_results(data: Any, filename: str, fileformat: Literal['json', 'csv', 'html', 'html_table']) None[source]¶
Save results to a file in the specified format.
Creates parent directories if they don’t exist. Handles various file formats with appropriate formatting and error handling.
- Parameters:
data – The data to save. Format depends on fileformat: - JSON: Any JSON-serializable data - CSV: List of dictionaries with consistent keys - HTML/HTML_TABLE: List of dictionaries for tabulate formatting
filename – Path where the file should be saved.
fileformat – Output format: - “json”: JSON format with indentation - “csv”: CSV format with headers - “html”: Complete HTML page with styling - “html_table”: Raw HTML table only
- Returns:
Results are saved to file, success/error messages printed to console.
- Return type:
None
- Raises:
Prints error messages to console but does not raise exceptions. –
- nadzoring.utils.formatters.truncate_string(s: str, max_width: int, placeholder: str = '...') str[source]¶
Truncate a string to fit within a specified width.
If the string exceeds the maximum width, it is truncated and the placeholder is appended to indicate truncation.
- Parameters:
s – The string to truncate.
max_width – Maximum allowed width in characters.
placeholder – String to append when truncated (default: “…”).
- Returns:
- Original string if within limits, otherwise truncated version
with placeholder appended.
- Return type:
str
Example
>>> truncate_string("very long string", 10) 'very lo...'