# Nadzoring — Full Documentation

## Source: README.md

<a id="readme-top"></a>

<div align="center">
  <p align="center">
    <img src="https://raw.githubusercontent.com/alexeev-prog/nadzoring/refs/heads/main/docs/nadzoring-long-preview.png">
    <p>An open source tool and python library for detecting website blocks, downdetecting and network analysis</p>
    <a href="https://alexeev-prog.github.io/nadzoring/v0.2.2"><strong>Explore the docs »</strong></a>
  </p>
  <p align="center">
    <a href="#-getting-started">Getting Started</a>
    ·
    <a href="#-basic-usage">Basic Usage</a>
    ·
    <a href="https://www.pitchhut.com/project/nadzoring-tool">Pitchhut</a>
    ·
    <a href="https://context7.com/alexeev-prog/nadzoring">Context7</a>
    ·
    <a href="https://deepwiki.com/alexeev-prog/nadzoring">Deepwiki</a>
    ·
    <a href="https://alexeev-prog.github.io/nadzoring/main">Latest Documentation</a>
    ·
    <a href="https://github.com/alexeev-prog/nadzoring/blob/main/LICENSE">License</a>
  </p>
</div>
<hr>
<p align="center">
    <img src="https://img.shields.io/github/languages/top/alexeev-prog/nadzoring?style=for-the-badge">
    <img src="https://img.shields.io/github/languages/count/alexeev-prog/nadzoring?style=for-the-badge">
    <img src="https://img.shields.io/badge/Maintained-yes-green.svg?style=for-the-badge">
    <img alt="GitHub License" src="https://img.shields.io/github/license/alexeev-prog/nadzoring?style=for-the-badge&logo=gnu">
    <img alt="GitHub forks" src="https://img.shields.io/github/forks/alexeev-prog/nadzoring?style=for-the-badge&logo=github">
    <img src="https://img.shields.io/github/stars/alexeev-prog/nadzoring?style=for-the-badge">
    <img src="https://img.shields.io/github/issues/alexeev-prog/nadzoring?style=for-the-badge">
    <img src="https://img.shields.io/github/last-commit/alexeev-prog/nadzoring?style=for-the-badge">
    <img alt="GitHub commits since latest release" src="https://img.shields.io/github/commits-since/alexeev-prog/nadzoring/latest?style=for-the-badge">
    <img alt="GitHub Release Date" src="https://img.shields.io/github/release-date-pre/alexeev-prog/nadzoring?style=for-the-badge">
    <img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/alexeev-prog/nadzoring/docs.yml?style=for-the-badge&logo=github&label=docs">
    <img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/alexeev-prog/nadzoring/python-package.yml?style=for-the-badge&logo=python&label=python%20package%20lint">
    <img src="https://img.shields.io/pypi/wheel/nadzoring?style=for-the-badge">
    <img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/nadzoring?style=for-the-badge">
    <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/nadzoring?style=for-the-badge">
    <img alt="GitHub contributors" src="https://img.shields.io/github/contributors/alexeev-prog/nadzoring?style=for-the-badge">
</p>
<p align="center">
    <img src="https://raw.githubusercontent.com/alexeev-prog/nadzoring/refs/heads/main/docs/pallet-0.png">
</p>

Nadzoring (from Russian "надзор" — supervision/oversight + the English "-ing" suffix) is a free and open-source command-line tool and Python library designed for in-depth network diagnostics, service availability monitoring, and website block detection. It empowers you to investigate connectivity issues, analyze network configurations, and audit security postures through a comprehensive suite of tools. From DNS diagnostics (including reverse lookups, poisoning detection, and delegation tracing) to ARP spoofing monitoring, SSL/TLS certificate analysis, HTTP security header auditing, email security validation (SPF/DKIM/DMARC), and subdomain discovery — Nadzoring brings together a wide range of capabilities in a single, consistent interface.

Built from the ground up with AI-friendliness in mind, Nadzoring is fully type-annotated, enforces a strict zero-warnings linter policy, and is architected according to SOLID principles with a strong emphasis on modularity and the Single Responsibility Principle (SRP). This architectural clarity ensures that the codebase remains maintainable, testable, and easy to extend. The project's high-quality typing and well-structured domain logic make it equally suitable for use as a reliable Python library in your own applications, as well as a powerful standalone CLI tool.

## Star History

<a href="https://www.star-history.com/?repos=alexeev-prog%2Fnadzoring&type=date&legend=top-left">
 <picture>
   <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=alexeev-prog/nadzoring&type=date&theme=dark&legend=top-left" />
   <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=alexeev-prog/nadzoring&type=date&legend=top-left" />
   <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=alexeev-prog/nadzoring&type=date&legend=top-left" />
 </picture>
</a>

<p align="center">
    <a href="https://deepwiki.com/alexeev-prog/nadzoring"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
    <a href='https://coveralls.io/github/alexeev-prog/nadzoring?branch=main'><img src='https://coveralls.io/repos/github/alexeev-prog/nadzoring/badge.svg?branch=main' alt='Coverage' /></a>
    <img src="https://img.shields.io/coderabbit/prs/github/alexeev-prog/nadzoring?utm_source=oss&utm_medium=github&utm_campaign=alexeev-prog%2Fnadzoring&labelColor=171717&color=FF570A&link=https%3A%2F%2Fcoderabbit.ai&label=CodeRabbit+Reviews" alt="CodeRabbit Pull Request Reviews">
    <img src="https://sloc.xyz/github/mutating/suby/?category=code" alt="Code lines">
    <img src="http://www.mypy-lang.org/static/mypy_badge.svg" alt="MyPy Badge">
    <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="ruff badge">
</p>

## Table of Contents

- [Getting Started](#getting-started)
    - [Prerequisites](#prerequisites)
    - [Installation](#installation)
    - [Running with Docker](#running-with-docker)
  - [Basic Usage](#basic-usage)
    - [Global Options](#global-options)
    - [Shell Completions](#shell-completions)
      - [Bash](#bash)
      - [Zsh](#zsh)
      - [Fish](#fish)
      - [PowerShell](#powershell)
      - [Testing Completions](#testing-completions)
      - [Manual Activation (without saving to profile)](#manual-activation-without-saving-to-profile)
      - [Troubleshooting Completions](#troubleshooting-completions)
      - [Completions Commands Reference](#completions-commands-reference)
  - [Documentation](#documentation)
  - [Contributing](#contributing)
  - [License \& Support](#license--support)

---

# Getting Started

### Prerequisites

- Python 3.12+
- pip

Optional system utilities:

| Utility | Required by |
|---------|-------------|
| `traceroute` / `tracepath` | `network-base traceroute` (Linux) |
| `whois` | `network-base whois` |
| `ip` / `route` | `network-base params`, `network-base route` |
| `net-tools` | `network-base params` on some Linux distros (`sudo apt install net-tools`) |
| `ss` | `network-base connections` (Linux) |
| `dig` / `nslookup` | `security check-email` (DNS TXT lookups; `dnspython` used when available) |

> **Note:** The Python package `netifaces` (used by `network-base params`) is distributed as source code and requires compilation on Linux. If you encounter errors during installation (e.g., `gcc: command not found`), install the required build tools first:
> `sudo apt update && sudo apt install build-essential python3-dev` (Debian/Ubuntu)
> or the equivalent for your distribution. On other platforms (Windows, macOS) pre‑compiled wheels are usually available.

### Installation

```bash
pip install nadzoring
```

Verify:

```bash
nadzoring --help
```

**Development version:**

```bash
pip install git+https://github.com/alexeev-prog/nadzoring.git
```

### Running with Docker

For Linux users, Docker provides the easiest and most stable way to run Nadzoring without system dependency issues. The container comes with all necessary network capabilities pre-configured.

> **📘 Detailed Docker Guide:** See [Docker.md](Docker.md) for complete Docker setup instructions, including native Windows alternatives, development tips, and troubleshooting.

**Quick start with Docker:**

```bash
# Clone the repository
git clone https://github.com/alexeev-prog/nadzoring.git
cd nadzoring

# Build the Docker image
docker build -t nadzoring:latest .

# Create a convenient alias (add to ~/.bashrc or ~/.zshrc)
alias nadzoring='docker run --rm -it \
  --network host \
  --cap-add=NET_ADMIN \
  --cap-add=NET_RAW \
  nadzoring:latest'

# Now use Nadzoring normally
nadzoring --help
nadzoring dns resolve google.com
nadzoring network-base port-scan 192.168.1.0/24
nadzoring arp detect-spoofing
```

**Benefits of using Docker:**
- [x] **Isolated environment** — No Python version conflicts or dependency issues
- [x] **Easy updates** — Just rebuild the image with `git pull && docker build`
- [x] **No system modifications** — Leaves your host system untouched
- [x] **Consistent behavior** — Works the same across different Linux distributions
- [x] **Network capabilities** — Pre-configured with NET_ADMIN and NET_RAW for full functionality

**Platform recommendation:**

| Platform | Recommended Method | Best For |
|----------|-------------------|----------|
| **Linux** | Docker (with alias) | Servers, CI/CD |
| **Linux** | Native (pipx) | Most users, development |
| **Windows** | Native (pipx) | Windows-users |

> **Note for Windows users:** Docker on Windows has limitations with raw sockets and local network access. Native installation via pipx is strongly recommended for Windows. See [Docker.md](Docker.md) for Windows-specific guidance.

---

## Basic Usage

Nadzoring uses a hierarchical command structure: `nadzoring <group> <command> [OPTIONS]`.
The four main groups are `dns`, `network-base`, `security`, and `arp`.

### Global Options

These options work with every command:

| Option | Short | Description | Default |
|--------|-------|-------------|---------|
| `--verbose` | | Enable debug output with execution timing | `False` |
| `--quiet` | | Suppress non-error output | `False` |
| `--no-color` | | Disable colored output | `False` |
| `--output` | `-o` | Output format: `table`, `json`, `csv`, `html`, `html_table`, `yaml` | `table` |
| `--save` | | Save results to file | None |
| `--timeout` | | Lifetime timeout for the entire operation (seconds) | `30.0` |
| `--connect-timeout` | | Connection timeout (seconds). Falls back to `--timeout` | `5.0` |
| `--read-timeout` | | Read timeout (seconds). Falls back to `--timeout` | `10.0` |
| `--proxy` | | SOCKS5 proxy URL (e.g., `socks5://127.0.0.1:1080`). All HTTP/HTTPS traffic uses this proxy. | None |

**Timeout resolution order:**
1. Explicit `--connect-timeout` / `--read-timeout`
2. Generic `--timeout` (applies to both phases when phase-specific not set)
3. Module-level defaults (shown above)

### Shell Completions

Nadzoring provides tab-completion support for **bash**, **zsh**, **fish**, and **PowerShell**. Enable it for your preferred shell using the commands below.

#### Bash

Add to `~/.bashrc` (or `~/.bash_profile` on macOS):

```bash
echo 'eval "$(nadzoring completion bash)"' >> ~/.bashrc
source ~/.bashrc
```

Alternative — save to a file and source it:

```bash
nadzoring completion bash > ~/.nadzoring-complete.bash
echo 'source ~/.nadzoring-complete.bash' >> ~/.bashrc
```

#### Zsh

Add to `~/.zshrc`:

```bash
echo 'eval "$(nadzoring completion zsh)"' >> ~/.zshrc
source ~/.zshrc
```

Or save to a file in your `fpath`:

```bash
nadzoring completion zsh > "${fpath[1]}/_nadzoring"
```

#### Fish

Save directly to Fish completions directory:

```bash
nadzoring completion fish > ~/.config/fish/completions/nadzoring.fish
```

Or source it temporarily:

```bash
nadzoring completion fish | source
```

#### PowerShell

Add to your PowerShell profile (`$PROFILE`):

```powershell
nadzoring completion powershell >> $PROFILE
```

To reload the profile immediately:

```powershell
. $PROFILE
```

Or use it in the current session only:

```powershell
nadzoring completion powershell | Invoke-Expression
```

#### Testing Completions

After installation, type `nadzoring ` followed by **TAB** to see available commands:

```bash
nadzoring [TAB]
# Should show: arp  completion  dns  network-base  security
```

Type a command followed by space and **TAB** to see options:

```bash
nadzoring dns [TAB]
# Should show: resolve  reverse  check  trace  compare  health  benchmark  poisoning  monitor
```

#### Manual Activation (without saving to profile)

If you don't want to modify your shell profile, you can activate completions manually:

```bash
# Bash / Zsh
source <(nadzoring completion bash)

# Fish
nadzoring completion fish | source

# PowerShell
nadzoring completion powershell | Invoke-Expression
```

#### Troubleshooting Completions

**Completions not working?** Check these common issues:

1. **Shell not reloaded** — restart your terminal or run `source ~/.bashrc` (bash) / `source ~/.zshrc` (zsh)
2. **Wrong shell** — ensure you're using the correct completion command for your shell
3. **PATH issue** — verify `nadzoring` is in your PATH: `which nadzoring`
4. **Completion not registered** — run the activation command directly to see if there are any errors

**Debugging bash completions:**

```bash
# Enable debug output
set -x
nadzoring [TAB]
set +x
```

**Check if completion is registered:**

```bash
# Bash
complete -p | grep nadzoring
# Should output: complete -o nosort -F _nadzoring_completion nadzoring

# Zsh
echo $fpath | grep nadzoring
```

**Show installation hints:**

```bash
nadzoring completion hints bash      # For bash
nadzoring completion hints zsh       # For zsh
nadzoring completion hints fish      # For fish
nadzoring completion hints powershell  # For PowerShell
```

#### Completions Commands Reference

| Command | Description |
|---------|-------------|
| `nadzoring completion bash` | Generate bash completion script |
| `nadzoring completion zsh` | Generate zsh completion script |
| `nadzoring completion fish` | Generate fish completion script |
| `nadzoring completion powershell` | Generate PowerShell completion script |
| `nadzoring completion hints <shell>` | Show detailed installation hints |

For complete command reference, Python API documentation, and advanced examples, see the **[full documentation](https://alexeev-prog.github.io/nadzoring/main)**.

---

## Documentation

| Version | Link | Status |
|---------|------|--------|
| **main** | [Latest (development)](https://alexeev-prog.github.io/nadzoring/main) | 🟡 Development |
| **v0.2.2** | [Release](https://alexeev-prog.github.io/nadzoring/v0.2.2) | 🟢 Stable |
| v0.2.1 | [Release](https://alexeev-prog.github.io/nadzoring/v0.2.1) | 🟢 Stable |
| v0.2.0 | [Release](https://alexeev-prog.github.io/nadzoring/v0.2.0) | 🟢 Stable |
| v0.1.9 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.9) | ⚪ Legacy |
| v0.1.8 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.8) | ⚪ Legacy |
| v0.1.7 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.7) | ⚪ Legacy |
| v0.1.6 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.6) | ⚪ Legacy |
| v0.1.5 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.5) | ⚪ Legacy |
| v0.1.4 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.4) | ⚪ Legacy |
| v0.1.3 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.3) | ⚪ Legacy |
| v0.1.2 | [Legacy](https://alexeev-prog.github.io/nadzoring/v0.1.2) | ⚪ Legacy |
| v0.1.1 | [First version](https://alexeev-prog.github.io/nadzoring/v0.1.1) | ⚪ Legacy |

The documentation site includes:
- [Complete CLI Command Reference](https://alexeev-prog.github.io/nadzoring/main/commands/all_commands.html) — all commands with options
- [Python API Examples](https://alexeev-prog.github.io/nadzoring/main/api_examples.html) — practical API usage
- [Code Examples](https://alexeev-prog.github.io/nadzoring/main/code_examples.html) — real-world scenarios
- [Error Handling guide](https://alexeev-prog.github.io/nadzoring/main/error_handling.html) — complete reference of all error patterns and return values
- [Architecture overview](https://alexeev-prog.github.io/nadzoring/main/architecture.html) — layer design, SRP/DRY/KISS principles applied
- [DNS monitoring guide](https://alexeev-prog.github.io/nadzoring/main/monitoring_dns.html) — systemd, cron, trend analysis

---

### LLM-friendly documentation

For AI assistants and language models:

- [`llms.txt`](llms.txt) — concise project overview and links to essential documentation.
- [`llms-full.txt`](llms-full.txt) — consolidated project documentation for larger context windows.

---

## Contributing

Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) before submitting a pull request.

**Workflow:**

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

**Areas we'd love help with:**

- Additional DNS record type support
- New health check validation rules
- CDN network database expansion
- Performance optimisations
- Additional output formats
- ARP detection heuristics
- New network diagnostic commands
- Extended security auditing (HSTS preload check, certificate transparency monitoring, CAA record validation)

---

## License & Support

This project is licensed under the **GNU GPL v3 License** — see [LICENSE](https://github.com/alexeev-prog/nadzoring/blob/main/LICENSE) for details.

For commercial support or enterprise features, contact [alexeev.dev@mail.ru](mailto:alexeev.dev@mail.ru).

[📖 Explore Docs](https://alexeev-prog.github.io/nadzoring) · [🐛 Report Issue](https://github.com/alexeev-prog/nadzoring/issues)

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---
Copyright © 2025 Alexeev Bronislav. Distributed under GNU GPL v3 license.


## Source: docs/source/quickstart.rst

Quick Start
===========

After installing Nadzoring (see :doc:`installation`), you can start using it immediately.
This page covers the most common workflows with practical examples.

----

Basic Structure
---------------

Nadzoring uses a three-level command hierarchy:

.. code-block:: text

   nadzoring <group> <command> [OPTIONS] [ARGUMENTS]

The four command groups are ``dns``, ``network-base``, ``security``, and ``arp``.

----

Global Options
--------------

Every command supports these flags:

.. list-table::
   :header-rows: 1
   :widths: 20 10 55 15

   * - Option
     - Short
     - Description
     - Default
   * - ``--verbose``
     -
     - Show debug logs and execution timing
     - ``False``
   * - ``--quiet``
     -
     - Suppress all output except results
     - ``False``
   * - ``--no-color``
     -
     - Disable colored output
     - ``False``
   * - ``--output``
     - ``-o``
     - Output format: ``table``, ``json``, ``csv``, ``html``, ``html_table``, ``yaml``
     - ``table``
   * - ``--save``
     -
     - Save results to a file
     - None
   * - ``--timeout``
     -
     - Lifetime timeout for the entire operation (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds). Falls back to ``--timeout``.
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds). Falls back to ``--timeout``.
     - ``10.0``
   * - ``--proxy``
     -
     - SOCKS5 proxy URL (e.g., ``socks5://127.0.0.1:1080``). Affects all HTTP/HTTPS requests.
     - None

**Timeout resolution order:**
1. Explicit phase-specific flag (``--connect-timeout`` / ``--read-timeout``)
2. Generic ``--timeout`` flag
3. Module default shown above

----

1. Check Your Network Configuration
--------------------------------------

Get a full summary of your local network interface:

.. code-block:: bash

   nadzoring network-base params

Output includes interface name, IPv4/IPv6 addresses, gateway IP, MAC address,
and public IP address.

To export as JSON for scripting:

.. code-block:: bash

   nadzoring network-base params -o json --save net_params.json

**Python API:**

.. code-block:: python

   from nadzoring.network_base.network_params import network_param

   info = network_param()
   print(info["IPv4 address"])        # '192.168.1.42'
   print(info["Router ip-address"])   # '192.168.1.1'
   print(info["Public IP address"])   # your external IP

----

2. Resolve a Hostname to IP
-----------------------------

Translate a hostname to its IPv4 address:

.. code-block:: bash

   nadzoring network-base host-to-ip example.com

Look up specific DNS record types:

.. code-block:: bash

   # A record (IPv4)
   nadzoring dns resolve example.com

   # All record types at once
   nadzoring dns resolve -t ALL example.com

   # MX and TXT records
   nadzoring dns resolve -t MX -t TXT gmail.com

   # Show TTL values
   nadzoring dns resolve --show-ttl -t A github.com

   # Use a specific nameserver
   nadzoring dns resolve -n 8.8.8.8 example.com

   # Custom timeout for slow networks
   nadzoring dns resolve --connect-timeout 10 --read-timeout 20 example.com

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.utils import resolve_with_timer
   from nadzoring.utils.timeout import TimeoutConfig

   # Default timeouts
   result = resolve_with_timer("example.com", "A")
   if not result["error"]:
       print(result["records"])       # ['93.184.216.34']
       print(result["response_time"]) # e.g. 42.5 ms

   # Custom timeouts
   config = TimeoutConfig(connect=3.0, read=8.0, lifetime=20.0)
   result = resolve_with_timer("example.com", "A", timeout_config=config)

----

3. Parse a URL
---------------

Break a URL into its components (scheme, hostname, port, path, query, fragment):

.. code-block:: bash

   nadzoring network-base parse-url https://example.com/path?q=1#section

**Python API:**

.. code-block:: python

   from nadzoring.network_base.parse_url import parse_url

   result = parse_url("https://user:pass@example.com:8080/path?key=value#frag")
   print(result["protocol"])   # 'https'
   print(result["hostname"])   # 'example.com'
   print(result["port"])       # 8080
   print(result["username"])   # 'user'
   print(result["query_params"])  # [('key', 'value')]

----

4. Comprehensive Domain Information
-------------------------------------

Retrieve WHOIS registration data, DNS records, IP geolocation, and reverse DNS
for a domain in a single command:

.. code-block:: bash

   nadzoring network-base domain-info example.com

   # Multiple domains, save as JSON
   nadzoring network-base domain-info -o json --save domain_info.json \
       google.com github.com cloudflare.com

**Python API:**

.. code-block:: python

   from nadzoring.network_base.domain_info import get_domain_info

   info = get_domain_info("example.com")

   print(info["whois"]["registrar"])
   print(info["dns"]["ipv4"])          # '93.184.216.34'
   print(info["dns"]["records"]["MX"]) # list of MX records
   print(info["geolocation"]["country"])
   print(info["reverse_dns"])          # hostname or None

----

5. Reverse DNS Lookup
-----------------------

Find the hostname associated with an IP address (PTR record):

.. code-block:: bash

   # Single IP
   nadzoring dns reverse 8.8.8.8

   # Multiple IPs at once
   nadzoring dns reverse 1.1.1.1 8.8.8.8 9.9.9.9

   # Use a custom nameserver
   nadzoring dns reverse -n 208.67.222.222 8.8.4.4

   # Save results as JSON
   nadzoring dns reverse -o json --save reverse.json 8.8.8.8

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.reverse import reverse_dns

   result = reverse_dns("8.8.8.8")
   if result["error"]:
       print(result["error"])  # 'No PTR record'
   else:
       print(result["hostname"])       # 'dns.google'
       print(result["response_time"])  # e.g. 18.34 ms

----

6. Ping a Host
---------------

Check basic network reachability:

.. code-block:: bash

   # Single host
   nadzoring network-base ping google.com

   # Multiple hosts at once
   nadzoring network-base ping 8.8.8.8 1.1.1.1 cloudflare.com

**Python API:**

.. code-block:: python

   from nadzoring.network_base.ping_address import ping_addr

   # Works with IPs, hostnames, and full URLs
   reachable = ping_addr("8.8.8.8")
   reachable = ping_addr("https://google.com")

----

7. HTTP Probe a URL
---------------------

Measure DNS resolution time, time-to-first-byte, and total download time:

.. code-block:: bash

   nadzoring network-base http-ping https://example.com

   # With response headers
   nadzoring network-base http-ping --show-headers https://github.com

   # Custom timeout, disable SSL verification
   nadzoring network-base http-ping --timeout 5 --no-ssl-verify https://self-signed.badssl.com

   # Phase-specific timeouts
   nadzoring network-base http-ping --connect-timeout 3 --read-timeout 15 https://slow.example.com

**Python API:**

.. code-block:: python

   from nadzoring.network_base.http_ping import http_ping
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=2.0, read=10.0)
   result = http_ping("https://example.com", timeout_config=config)
   if not result.error:
       print(result.status_code)    # 200
       print(result.dns_ms)         # e.g. 12.5
       print(result.ttfb_ms)        # e.g. 87.3
       print(result.total_ms)       # e.g. 134.6

----

8. DNS Health Check
---------------------

Score a domain's DNS configuration from 0 to 100:

.. code-block:: bash

   nadzoring dns health example.com

Scoring thresholds:

- **80–100** → Healthy
- **50–79** → Degraded
- **0–49** → Unhealthy

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.health import health_check_dns

   result = health_check_dns("example.com")
   print(result["score"])   # e.g. 85
   print(result["status"])  # 'healthy' | 'degraded' | 'unhealthy'
   for issue in result["issues"]:
       print("ISSUE:", issue)

----

9. Validate DNS Records
------------------------

Run a detailed DNS check including MX priority and SPF/DKIM validation:

.. code-block:: bash

   nadzoring dns check example.com

   # Check specific record types only
   nadzoring dns check -t MX -t TXT gmail.com

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.health import check_dns

   result = check_dns(
       "example.com",
       record_types=["MX", "TXT"],
       validate_mx=True,
       validate_txt=True,
   )
   print(result["records"])      # {'MX': ['10 mail.example.com'], ...}
   print(result["validations"])  # {'mx': {'valid': True, 'issues': []}}

----

10. Trace the DNS Resolution Path
----------------------------------

Follow the delegation chain from root servers to the authoritative answer:

.. code-block:: bash

   nadzoring dns trace example.com

   # Start from a specific nameserver instead of root
   nadzoring dns trace -n 8.8.8.8 google.com

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.trace import trace_dns

   result = trace_dns("example.com")
   for hop in result["hops"]:
       print(hop["nameserver"], hop["response_time"], hop.get("records"))

----

11. Compare DNS Servers
-----------------------

Detect discrepancies between multiple resolvers for the same domain:

.. code-block:: bash

   nadzoring dns compare example.com

   # Custom servers and record types
   nadzoring dns compare -t A -t MX -s 8.8.8.8 -s 1.1.1.1 -s 9.9.9.9 example.com

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.compare import compare_dns_servers

   result = compare_dns_servers(
       "example.com",
       servers=["8.8.8.8", "1.1.1.1", "9.9.9.9"],
       record_types=["A", "MX"],
   )
   if result["differences"]:
       for diff in result["differences"]:
           print(f"Server {diff['server']} returned different records")

----

12. Detect DNS Poisoning
--------------------------

Check whether a domain's DNS responses show signs of poisoning, censorship,
or unusual CDN routing:

.. code-block:: bash

   nadzoring dns poisoning example.com

   # Custom control server with additional record types checked
   nadzoring dns poisoning -c 1.1.1.1 -a MX -a TXT google.com

   # Save as HTML report
   nadzoring dns poisoning -o html --save poisoning_report.html twitter.com

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.poisoning import check_dns_poisoning

   result = check_dns_poisoning("example.com")
   print(f"Level: {result.get('poisoning_level', 'NONE')}")
   print(f"Confidence: {result.get('confidence', 0):.0f}%")

----

13. Benchmark DNS Servers
---------------------------

Find the fastest DNS resolver for your location:

.. code-block:: bash

   # Benchmark all well-known public servers
   nadzoring dns benchmark

   # Custom servers, 20 queries each
   nadzoring dns benchmark -s 8.8.8.8 -s 1.1.1.1 -s 9.9.9.9 --queries 20

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.benchmark import benchmark_dns_servers

   results = benchmark_dns_servers(
       servers=["8.8.8.8", "1.1.1.1", "9.9.9.9"],
       queries=10,
   )
   for r in results:
       print(f"{r['server']}: avg={r['avg_response_time']:.1f}ms")

----

14. Continuous DNS Monitoring
-------------------------------

Monitor DNS health and performance over time, with alerts and logging:

.. code-block:: bash

   nadzoring dns monitor example.com \
       --interval 60 \
       --log-file dns_monitor.jsonl

   # Analyse the log later
   nadzoring dns monitor-report dns_monitor.jsonl

**Python API:**

.. code-block:: python

   from nadzoring.dns_lookup.monitor import DNSMonitor, MonitorConfig, load_log
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=2.0, read=8.0)

   # Monitor for 10 cycles
   monitor_config = MonitorConfig(
       domain="example.com",
       interval=10.0,
       timeout_config=config,
   )
   monitor = DNSMonitor(monitor_config)
   history = monitor.run_cycles(10)

   # Analyse existing log
   cycles = load_log("dns_monitor.jsonl")
   print(f"Cycles: {len(cycles)}")

----

15. Scan Ports
---------------

Discover open ports and running services on a target:

.. code-block:: bash

   # Fast scan (common ports)
   nadzoring network-base port-scan example.com

   # Full scan (all 65535 ports)
   nadzoring network-base port-scan --mode full 192.168.1.1

   # Custom range
   nadzoring network-base port-scan --mode custom --ports 1-1024 example.com

   # With custom timeouts
   nadzoring network-base port-scan --connect-timeout 1 --read-timeout 3 example.com

**Python API:**

.. code-block:: python

   from nadzoring.network_base.port_scanner import ScanConfig, scan_ports
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=1.5, read=5.0)
   scan_config = ScanConfig(targets=["example.com"], mode="fast", timeout_config=config)
   for result in scan_ports(scan_config):
       print("Open ports:", result.open_ports)

----

16. Detect Service on Port
---------------------------

Actively connect to a port and identify the running service by banner:

.. code-block:: bash

   nadzoring network-base detect-service example.com 80 443 22

**Python API:**

.. code-block:: python

   from nadzoring.network_base.service_detector import detect_service_on_host
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=3.0, read=8.0)
   result = detect_service_on_host("example.com", 80, timeout_config=config)
   print(result.detected_service or result.guessed_service)

----

17. SSL/TLS Certificate Check
-------------------------------

Inspect SSL/TLS certificates for expiry and security:

.. code-block:: bash

   # Compact summary
   nadzoring security check-ssl example.com

   # 30-day warning window, full details
   nadzoring security check-ssl --days-before 30 --full example.com

   # Custom timeout for slow servers
   nadzoring security check-ssl --connect-timeout 10 example.com

**Python API:**

.. code-block:: python

   from nadzoring.security.check_website_ssl_cert import check_ssl_certificate
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=3.0, read=10.0)
   result = check_ssl_certificate("example.com", days_before=14, timeout_config=config)
   print(result["status"], result["remaining_days"])
   print(result["protocols"]["supported"])

----

18. HTTP Security Headers
--------------------------

Audit HTTP security headers for a URL:

.. code-block:: bash

   nadzoring security check-headers https://example.com

**Python API:**

.. code-block:: python

   from nadzoring.security.http_headers import check_http_security_headers
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=5.0, read=15.0)
   result = check_http_security_headers("https://example.com", timeout_config=config)
   print(result["score"])    # 0–100 coverage score
   print(result["missing"])  # list of absent headers

----

19. Email Security
-------------------

Validate SPF, DKIM, and DMARC records:

.. code-block:: bash

   nadzoring security check-email example.com

**Python API:**

.. code-block:: python

   from nadzoring.security.email_security import check_email_security

   result = check_email_security("example.com")
   print(result["overall_score"])         # 0–3
   print(result["spf"]["all_qualifier"])  # '~'
   print(result["dmarc"]["policy"])       # 'reject'

----

20. Subdomain Discovery
------------------------

Find subdomains using CT logs and DNS brute-force:

.. code-block:: bash

   nadzoring security subdomains example.com

**Python API:**

.. code-block:: python

   from nadzoring.security.subdomain_scan import scan_subdomains
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=2.0, read=8.0)
   results = scan_subdomains("example.com", timeout_config=config)
   for r in results:
       print(r["subdomain"], r["ip"], r["source"])

----

21. Continuous SSL Monitoring
-------------------------------

Monitor SSL certificates for changes and expiry:

.. code-block:: bash

   nadzoring security watch-ssl example.com

**Python API:**

.. code-block:: python

   from nadzoring.security.ssl_monitor import SSLMonitor
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=3.0, read=10.0)
   monitor = SSLMonitor(["example.com"], interval=3600, timeout_config=config)
   monitor.set_alert_callback(lambda d, m: print(f"ALERT {d}: {m}"))
   monitor.run_cycles(5)

----

22. ARP Cache and Spoofing Detection
--------------------------------------

Inspect the local ARP cache:

.. code-block:: bash

   nadzoring arp cache

Detect spoofing statically or in real-time:

.. code-block:: bash

   nadzoring arp detect-spoofing
   nadzoring arp monitor-spoofing --interface eth0 --timeout 60

**Python API:**

.. code-block:: python

   from nadzoring.arp.cache import ARPCache
   from nadzoring.arp.realtime import ARPRealtimeDetector
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(lifetime=45.0)
   cache = ARPCache()
   for entry in cache.get_cache():
       print(entry.ip_address, entry.mac_address)

   detector = ARPRealtimeDetector()
   alerts = detector.monitor(interface="eth0", count=50, timeout_config=config)

----

Output Formats
--------------

Use ``-o`` to change how results are displayed or saved:

.. code-block:: bash

   nadzoring dns resolve -o json example.com
   nadzoring dns health -o html --save health_report.html example.com
   nadzoring network-base connections -o csv --save conns.csv
   nadzoring security check-ssl -o json example.com

Available formats: ``table`` (default), ``json``, ``csv``, ``html``, ``html_table``, ``yaml``

----

Getting Help
------------

.. code-block:: bash

   # List all command groups
   nadzoring --help

   # List commands in a group
   nadzoring dns --help
   nadzoring network-base --help
   nadzoring security --help
   nadzoring arp --help

   # Help for a specific command
   nadzoring dns reverse --help
   nadzoring network-base port-scan --help
   nadzoring security check-ssl --help


## Source: docs/source/commands/all_commands.rst

===============
CLI Command Reference
===============

This page documents all CLI commands, their options, output formats, timeout configuration, and error handling patterns.

----

DNS Commands
------------

dns resolve
~~~~~~~~~~~

Resolve DNS records for one or more domains.

.. code-block:: bash

   nadzoring dns resolve [OPTIONS] DOMAINS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--type``
     - ``-t``
     - Record type: A, AAAA, CNAME, MX, NS, TXT, ALL
     - ``A``
   * - ``--nameserver``
     - ``-n``
     - Nameserver IP to use
     - System default
   * - ``--short``
     -
     - Compact output
     - ``False``
   * - ``--show-ttl``
     -
     - Show TTL value
     - ``False``
   * - ``--format-style``
     -
     - Output style: standard, bind, host, dig
     - ``standard``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Examples:**

.. code-block:: bash

   # A record lookup
   nadzoring dns resolve google.com

   # Multiple record types
   nadzoring dns resolve -t MX -t TXT -t A example.com

   # All record types with a specific nameserver
   nadzoring dns resolve -t ALL -n 8.8.8.8 github.com

   # Show TTL values
   nadzoring dns resolve --show-ttl --type A cloudflare.com

   # Custom timeouts for slow networks
   nadzoring dns resolve --connect-timeout 10 --read-timeout 20 example.com

----

dns reverse
~~~~~~~~~~~

Perform reverse DNS lookups (PTR records) to find the hostname for an IP address.

.. code-block:: bash

   nadzoring dns reverse [OPTIONS] IP_ADDRESSES...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 70

   * - Option
     - Short
     - Description
   * - ``--nameserver``
     - ``-n``
     - Nameserver IP to use

**Examples:**

.. code-block:: bash

   # Single IP
   nadzoring dns reverse 8.8.8.8

   # Multiple IPs
   nadzoring dns reverse 1.1.1.1 8.8.8.8 9.9.9.9

   # Use a specific nameserver
   nadzoring dns reverse -n 208.67.222.222 8.8.4.4

   # Save as JSON
   nadzoring dns reverse -o json --save reverse_lookup.json 8.8.8.8 1.1.1.1

----

dns check
~~~~~~~~~

Perform a comprehensive DNS check including MX priority validation and SPF/DKIM analysis.

.. code-block:: bash

   nadzoring dns check [OPTIONS] DOMAINS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--nameserver``
     - ``-n``
     - Nameserver IP
     - System default
   * - ``--types``
     - ``-t``
     - Record types to check
     - ALL
   * - ``--validate-mx``
     -
     - Validate MX priority uniqueness
     - ``False``
   * - ``--validate-txt``
     -
     - Validate SPF and DKIM TXT records
     - ``False``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Examples:**

.. code-block:: bash

   # Full DNS check
   nadzoring dns check example.com

   # Check MX and TXT only with validation
   nadzoring dns check -t MX -t TXT --validate-mx --validate-txt gmail.com

   # Multiple domains
   nadzoring dns check -n 9.9.9.9 google.com cloudflare.com

----

dns trace
~~~~~~~~~

Trace the complete DNS resolution delegation chain from root to authoritative nameserver.

.. code-block:: bash

   nadzoring dns trace [OPTIONS] DOMAIN

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--nameserver``
     - ``-n``
     - Starting nameserver
     - root ``198.41.0.4``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Examples:**

.. code-block:: bash

   # Trace from root servers
   nadzoring dns trace example.com

   # Start trace from a specific nameserver
   nadzoring dns trace -n 8.8.8.8 google.com

   # Verbose with timing
   nadzoring dns trace -v github.com

----

dns compare
~~~~~~~~~~~

Compare DNS responses from multiple servers and detect discrepancies.

.. code-block:: bash

   nadzoring dns compare [OPTIONS] DOMAIN

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--servers``
     - ``-s``
     - DNS servers to compare
     - ``8.8.8.8``, ``1.1.1.1``, ``9.9.9.9``
   * - ``--type``
     - ``-t``
     - Record types to compare
     - ``A``

**Examples:**

.. code-block:: bash

   # Compare A records across default servers
   nadzoring dns compare example.com

   # Compare MX records with custom servers
   nadzoring dns compare -t MX -s 8.8.8.8 -s 208.67.222.222 -s 9.9.9.9 gmail.com

   # Multiple record types
   nadzoring dns compare -t A -t AAAA -t NS cloudflare.com

----

dns health
~~~~~~~~~~

Perform a scored DNS health check across all standard record types.

.. code-block:: bash

   nadzoring dns health [OPTIONS] DOMAIN

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--nameserver``
     - ``-n``
     - Nameserver IP
     - System default
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Health score:** **80–100** = Healthy · **50–79** = Degraded · **0–49** = Unhealthy

**Examples:**

.. code-block:: bash

   nadzoring dns health example.com
   nadzoring dns health -n 1.1.1.1 google.com
   nadzoring dns health -o json --save health.json example.com

----

dns benchmark
~~~~~~~~~~~~~

Benchmark DNS server response times across multiple servers.

.. code-block:: bash

   nadzoring dns benchmark [OPTIONS]

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--domain``
     - ``-d``
     - Domain to query
     - ``google.com``
   * - ``--servers``
     - ``-s``
     - Servers to benchmark
     - All public servers
   * - ``--type``
     - ``-t``
     - Record type
     - ``A``
   * - ``--queries``
     - ``-q``
     - Queries per server
     - ``10``
   * - ``--parallel/--sequential``
     -
     - Run concurrently or one by one
     - ``parallel``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Examples:**

.. code-block:: bash

   nadzoring dns benchmark
   nadzoring dns benchmark -s 8.8.8.8 -s 1.1.1.1 -s 9.9.9.9 --queries 20
   nadzoring dns benchmark -t MX -d gmail.com --sequential
   nadzoring dns benchmark -o json --save benchmark.json

----

dns poisoning
~~~~~~~~~~~~~

Detect DNS poisoning, censorship, or unusual CDN routing for a domain.

.. code-block:: bash

   nadzoring dns poisoning [OPTIONS] DOMAIN

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--control-server``
     - ``-c``
     - Trusted control resolver
     - ``8.8.8.8``
   * - ``--test-servers``
     - ``-t``
     - Servers to test against control
     - All public servers
   * - ``--type``
     - ``-T``
     - Record type
     - ``A``
   * - ``--additional-types``
     - ``-a``
     - Extra record types from control server
     - None
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Severity levels:** ``NONE`` → ``LOW`` → ``MEDIUM`` → ``HIGH`` → ``CRITICAL`` / ``SUSPICIOUS``

**Examples:**

.. code-block:: bash

   nadzoring dns poisoning example.com
   nadzoring dns poisoning -c 1.1.1.1 -a MX -a TXT google.com
   nadzoring dns poisoning -o html --save poisoning_report.html twitter.com

----

dns monitor
~~~~~~~~~~~

Continuously monitor DNS health and performance for a domain. Logs each cycle to a structured JSONL file and fires configurable alerts when response time or success rate thresholds are breached.

.. code-block:: bash

   nadzoring dns monitor [OPTIONS] DOMAIN

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--nameservers``
     - ``-n``
     - DNS server to monitor (repeatable)
     - ``8.8.8.8``, ``1.1.1.1``
   * - ``--interval``
     - ``-i``
     - Seconds between monitoring cycles
     - ``60``
   * - ``--type``
     - ``-t``
     - Record type: A, AAAA, MX, NS, TXT
     - ``A``
   * - ``--queries``
     - ``-q``
     - Queries per server per cycle
     - ``3``
   * - ``--max-rt``
     -
     - Alert threshold: max avg response time (ms)
     - ``500``
   * - ``--min-success``
     -
     - Alert threshold: minimum success rate (0–1)
     - ``0.95``
   * - ``--no-health``
     -
     - Skip DNS health check each cycle
     - ``False``
   * - ``--log-file``
     - ``-l``
     - JSONL file to append all cycle results to
     - None
   * - ``--cycles``
     - ``-c``
     - Stop after N cycles (0 = indefinite)
     - ``0``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Examples:**

.. code-block:: bash

   # Monitor with default servers, save log
   nadzoring dns monitor example.com \
       --interval 60 \
       --log-file dns_monitor.jsonl

   # Strict thresholds — alert above 150 ms or below 99 % success
   nadzoring dns monitor example.com \
       -n 8.8.8.8 -n 1.1.1.1 -n 9.9.9.9 \
       --interval 30 \
       --max-rt 150 --min-success 0.99 \
       --log-file dns_monitor.jsonl

   # Run exactly 10 cycles and save a JSON report (great for CI)
   nadzoring dns monitor example.com --cycles 10 -o json --save report.json

   # Quiet mode for cron / systemd
   nadzoring dns monitor example.com \
       --quiet --log-file /var/log/nadzoring/dns_monitor.jsonl

----

dns monitor-report
~~~~~~~~~~~~~~~~~~

Analyse a JSONL log file produced by ``dns monitor``.

.. code-block:: bash

   nadzoring dns monitor-report [OPTIONS] LOG_FILE

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Option
     - Description
   * - ``--server``
     - Filter statistics to a specific server IP

**Examples:**

.. code-block:: bash

   nadzoring dns monitor-report dns_monitor.jsonl
   nadzoring dns monitor-report dns_monitor.jsonl --server 8.8.8.8 -o json

----

Network Base Commands
---------------------

ping
~~~~

Check reachability using ICMP ping.

.. code-block:: bash

   nadzoring network-base ping ADDRESSES...

**Examples:**

.. code-block:: bash

   nadzoring network-base ping 8.8.8.8
   nadzoring network-base ping google.com cloudflare.com 1.1.1.1
   nadzoring network-base ping -o json github.com

----

http-ping
~~~~~~~~~

Measure HTTP/HTTPS response timing and inspect headers.

.. code-block:: bash

   nadzoring network-base http-ping [OPTIONS] URLS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 60 10

   * - Option
     - Description
     - Default
   * - ``--timeout``
     - Request timeout (seconds) — sets both connect and read
     - ``10.0``
   * - ``--connect-timeout``
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     - Read timeout (seconds)
     - ``10.0``
   * - ``--no-ssl-verify``
     - Disable SSL certificate check
     - ``False``
   * - ``--no-redirects``
     - Do not follow redirects
     - ``False``
   * - ``--show-headers``
     - Include response headers
     - ``False``

**Output includes:** DNS time, TTFB, total download time, status code, content size, redirects.

**Examples:**

.. code-block:: bash

   nadzoring network-base http-ping https://example.com
   nadzoring network-base http-ping --show-headers https://github.com https://google.com
   nadzoring network-base http-ping --timeout 5 --no-ssl-verify https://self-signed.badssl.com
   nadzoring network-base http-ping -o csv --save http_metrics.csv https://api.github.com

----

host-to-ip
~~~~~~~~~~

Resolve hostnames to IP addresses with IPv4/IPv6 availability checks.

.. code-block:: bash

   nadzoring network-base host-to-ip HOSTNAMES...

**Examples:**

.. code-block:: bash

   nadzoring network-base host-to-ip google.com github.com cloudflare.com
   nadzoring network-base host-to-ip -o csv --save resolutions.csv example.com

----

parse-url
~~~~~~~~~

Parse a URL into its components (scheme, hostname, port, path, query, fragment, etc.).

.. code-block:: bash

   nadzoring network-base parse-url URLS...

**Examples:**

.. code-block:: bash

   nadzoring network-base parse-url https://example.com/path?q=1#section
   nadzoring network-base parse-url "postgresql://user:pass@localhost:5432/db"

----

geolocation
~~~~~~~~~~~

Get geographic location for IP addresses.

.. code-block:: bash

   nadzoring network-base geolocation IPS...

**Output:** latitude, longitude, country, city.

**Examples:**

.. code-block:: bash

   nadzoring network-base geolocation 8.8.8.8 1.1.1.1
   nadzoring network-base geolocation --save locations.json 8.8.8.8

----

params
~~~~~~

Show local network interface configuration.

.. code-block:: bash

   nadzoring network-base params [OPTIONS]

**Output:** interface name, IPv4, IPv6, gateway IP, MAC address, public IP.

**Examples:**

.. code-block:: bash

   nadzoring network-base params
   nadzoring network-base params -o json --save net_params.json

----

port-scan
~~~~~~~~~

Scan for open TCP/UDP ports on one or more targets.

.. code-block:: bash

   nadzoring network-base port-scan [OPTIONS] TARGETS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 60 10

   * - Option
     - Description
     - Default
   * - ``--mode``
     - ``fast``, ``full``, or ``custom``
     - ``fast``
   * - ``--ports``
     - Port list or range, e.g. ``22,80,443`` or ``1-1024``
     - None
   * - ``--protocol``
     - ``tcp`` or ``udp``
     - ``tcp``
   * - ``--timeout``
     - Socket timeout (seconds) — sets connect timeout
     - ``2.0``
   * - ``--connect-timeout``
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     - Read timeout (seconds) for banner grabbing
     - ``10.0``
   * - ``--workers``
     - Concurrent workers
     - ``50``
   * - ``--no-banner``
     - Disable banner grabbing
     - ``False``
   * - ``--show-closed``
     - Show closed ports
     - ``False``

**Scan modes:** **fast** = common ports · **full** = all 1–65535 · **custom** = your list or range.

**Examples:**

.. code-block:: bash

   nadzoring network-base port-scan example.com
   nadzoring network-base port-scan --mode full 192.168.1.1
   nadzoring network-base port-scan --mode custom --ports 22,80,443,8080 example.com
   nadzoring network-base port-scan --protocol udp --mode fast example.com
   nadzoring network-base port-scan -o json --save scan.json example.com

----

detect-service
~~~~~~~~~~~~~~

Actively connect to ports and detect actual running services by banner analysis.

.. code-block:: bash

   nadzoring network-base detect-service [OPTIONS] TARGET PORTS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 60 10

   * - Option
     - Description
     - Default
   * - ``--timeout``
     - Connection timeout (seconds) — sets connect timeout
     - ``3.0``
   * - ``--connect-timeout``
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     - Read timeout (seconds) for banner
     - ``10.0``
   * - ``--no-probe``
     - Disable sending protocol-specific probes
     - ``False``

**Examples:**

.. code-block:: bash

   # Detect services on common ports
   nadzoring network-base detect-service example.com 80 443 22

   # Database ports with longer timeout
   nadzoring network-base detect-service --connect-timeout 5 192.168.1.100 3306 5432 6379

----

port-service
~~~~~~~~~~~~

Identify the service typically running on a port number.

.. code-block:: bash

   nadzoring network-base port-service PORTS...

**Examples:**

.. code-block:: bash

   nadzoring network-base port-service 80 443 22 53 3306
   nadzoring network-base port-service -o json 8080 5432 27017

----

whois
~~~~~

Look up WHOIS registration data for domains or IP addresses.

.. note::

   **Requires** the system ``whois`` utility:
   - Debian/Ubuntu: ``sudo apt install whois``
   - macOS: ``brew install whois``
   - RHEL/Fedora: ``sudo dnf install whois``

.. code-block:: bash

   nadzoring network-base whois [OPTIONS] TARGETS...

**Examples:**

.. code-block:: bash

   nadzoring network-base whois example.com
   nadzoring network-base whois google.com cloudflare.com 8.8.8.8
   nadzoring network-base whois -o json --save whois_data.json github.com

----

domain-info
~~~~~~~~~~~

Retrieve comprehensive information about a domain in a single call. Aggregates WHOIS registration data, DNS record lookups (A, AAAA, MX, NS, TXT), IP geolocation for the primary resolved address, and reverse DNS — all returned as a structured response.

.. code-block:: bash

   nadzoring network-base domain-info [OPTIONS] DOMAINS...

**Examples:**

.. code-block:: bash

   nadzoring network-base domain-info example.com
   nadzoring network-base domain-info google.com github.com cloudflare.com
   nadzoring network-base domain-info -o json --save domain_report.json example.com

----

connections
~~~~~~~~~~~

List active TCP/UDP network connections.

.. code-block:: bash

   nadzoring network-base connections [OPTIONS]

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--protocol``
     - ``-p``
     - Filter: ``tcp``, ``udp``, ``all``
     - ``all``
   * - ``--state``
     - ``-s``
     - State filter substring, e.g. ``LISTEN``
     - None
   * - ``--no-process``
     -
     - Skip PID/process info
     - ``False``

**Examples:**

.. code-block:: bash

   nadzoring network-base connections
   nadzoring network-base connections --protocol tcp --state LISTEN
   nadzoring network-base connections --protocol udp --no-process
   nadzoring network-base connections -o csv --save connections.csv

----

traceroute
~~~~~~~~~~

Trace the network path to a host.

.. code-block:: bash

   nadzoring network-base traceroute [OPTIONS] TARGETS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 60 10

   * - Option
     - Description
     - Default
   * - ``--max-hops``
     - Maximum hops
     - ``30``
   * - ``--timeout``
     - Per-hop timeout (seconds) — sets connect timeout
     - ``2.0``
   * - ``--connect-timeout``
     - Per-hop timeout (seconds)
     - ``5.0``
   * - ``--sudo``
     - Run with sudo (Linux)
     - ``False``

.. note::

   **Linux privilege note:** ``traceroute`` needs raw-socket access.
   Either use ``--sudo``, run as root, or: ``sudo setcap cap_net_raw+ep $(which traceroute)``
   Nadzoring automatically falls back to ``tracepath`` (no root required) if traceroute fails.

**Examples:**

.. code-block:: bash

   nadzoring network-base traceroute google.com
   nadzoring network-base traceroute --max-hops 20 github.com cloudflare.com
   nadzoring network-base traceroute --sudo example.com
   nadzoring network-base traceroute -o html --save trace.html 8.8.8.8

----

route
~~~~~

Display the system IP routing table.

.. code-block:: bash

   nadzoring network-base route [OPTIONS]

**Examples:**

.. code-block:: bash

   nadzoring network-base route
   nadzoring network-base route -o json
   nadzoring network-base route --save routing_table.json

----

Security Commands
-----------------

The ``security`` group provides SSL/TLS certificate inspection, HTTP security header auditing, email security record validation, subdomain discovery, and continuous certificate monitoring.

.. code-block:: bash

   nadzoring security --help

----

security check-ssl
~~~~~~~~~~~~~~~~~~

Inspect the SSL/TLS certificate for one or more domains. Checks expiry, issuer, subject, Subject Alternative Names, key strength, domain match, and which TLS protocol versions the server accepts (TLSv1.0 through TLSv1.3).

By default only a compact summary is shown. Use ``--full`` to see all fields including the complete SAN list, protocol details, chain length, and raw serial number.

.. code-block:: bash

   nadzoring security check-ssl [OPTIONS] DOMAINS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--days-before``
     - ``-d``
     - Days before expiry to flag as ``warning`` status
     - ``7``
   * - ``--no-verify``
     -
     - Disable certificate chain verification (falls back automatically)
     - ``False``
   * - ``--full``
     -
     - Show all certificate fields instead of compact summary
     - ``False``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Status values:**

.. list-table::
   :header-rows: 1
   :widths: 20 80

   * - Status
     - Meaning
   * - ``valid``
     - Certificate is valid and not near expiry
   * - ``warning``
     - Fewer than ``--days-before`` days remaining
   * - ``expired``
     - Certificate has already expired
   * - ``error``
     - Could not connect or parse the certificate

**Examples:**

.. code-block:: bash

   # Basic check — compact summary table
   nadzoring security check-ssl example.com

   # Check multiple domains with a 30-day warning window
   nadzoring security check-ssl --days-before 30 google.com github.com cloudflare.com

   # Check without verifying the certificate chain (useful for self-signed certs)
   nadzoring security check-ssl --no-verify internal.corp.example.com

   # Full details including SAN list, protocol support, chain info
   nadzoring security check-ssl --full ya.ru

   # Save results as JSON for further processing
   nadzoring security check-ssl -o json --save ssl_report.json example.com github.com

----

security check-headers
~~~~~~~~~~~~~~~~~~~~~~

Analyse the HTTP security headers returned by one or more URLs. Checks for the presence of eleven recommended headers, flags deprecated headers (e.g. ``X-XSS-Protection``), identifies information-leaking headers (e.g. ``Server``, ``X-Powered-By``), and produces a 0–100 coverage score.

.. code-block:: bash

   nadzoring security check-headers [OPTIONS] URLS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 60 10

   * - Option
     - Description
     - Default
   * - ``--timeout``
     - Request timeout in seconds — sets both connect and read
     - ``10.0``
   * - ``--connect-timeout``
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     - Read timeout (seconds)
     - ``10.0``
   * - ``--no-verify``
     - Disable SSL certificate verification
     - ``False``

**Checked security headers:**

.. list-table::
   :header-rows: 1
   :widths: 40 60

   * - Header
     - Purpose
   * - ``Strict-Transport-Security``
     - Enforce HTTPS (HSTS)
   * - ``Content-Security-Policy``
     - Mitigate XSS and injection attacks
   * - ``X-Content-Type-Options``
     - Prevent MIME-type sniffing
   * - ``X-Frame-Options``
     - Prevent clickjacking
   * - ``X-XSS-Protection``
     - Legacy XSS filter (deprecated)
   * - ``Referrer-Policy``
     - Control referrer information leakage
   * - ``Permissions-Policy``
     - Restrict browser feature access
   * - ``Cross-Origin-Embedder-Policy``
     - Isolate cross-origin resources
   * - ``Cross-Origin-Opener-Policy``
     - Isolate browsing context
   * - ``Cross-Origin-Resource-Policy``
     - Control cross-origin resource sharing
   * - ``Cache-Control``
     - Prevent caching of sensitive responses

**Examples:**

.. code-block:: bash

   # Check a single URL
   nadzoring security check-headers https://example.com

   # Check multiple URLs and save results
   nadzoring security check-headers https://google.com https://github.com https://cloudflare.com

   # Skip SSL verification for internal/self-signed endpoints
   nadzoring security check-headers --no-verify https://internal.corp.example.com

   # Export as JSON for CI integration or dashboards
   nadzoring security check-headers -o json --save headers_audit.json https://example.com

   # Adjust timeout for slow servers
   nadzoring security check-headers --connect-timeout 20 https://slow-api.example.com

----

security check-email
~~~~~~~~~~~~~~~~~~~~

Validate the email security configuration for one or more domains. Checks SPF (Sender Policy Framework), DKIM (DomainKeys Identified Mail) by probing common selectors, and DMARC (Domain-based Message Authentication, Reporting and Conformance). Returns structured findings including detected issues and an overall score.

.. note::

   **Requires:** ``dig`` or ``nslookup`` to be available on the system, or ``dnspython`` installed in the Python environment (``pip install dnspython``). ``dnspython`` is preferred as it handles multi-chunk TXT records reliably.

.. code-block:: bash

   nadzoring security check-email [OPTIONS] DOMAINS...

**Examples:**

.. code-block:: bash

   # Check a single domain
   nadzoring security check-email gmail.com

   # Check multiple domains at once
   nadzoring security check-email google.com github.com cloudflare.com

   # Export full JSON report
   nadzoring security check-email -o json --save email_security.json example.com

   # Quiet mode for scripting — results only, no progress bars
   nadzoring security check-email --quiet example.com

----

security subdomains
~~~~~~~~~~~~~~~~~~~

Discover subdomains for a target domain using two complementary methods: certificate transparency (CT) log queries via `crt.sh <https://crt.sh>`_ and concurrent DNS brute-force using a built-in wordlist of 80+ common prefixes (or a custom wordlist file). Each result is tagged with its discovery source.

.. code-block:: bash

   nadzoring security subdomains [OPTIONS] DOMAIN

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 30 60 10

   * - Option
     - Description
     - Default
   * - ``--wordlist``
     - Path to a custom wordlist file (one prefix per line)
     - Built-in 80+ prefix list
   * - ``--threads``
     - Number of concurrent DNS resolution threads
     - ``20``
   * - ``--timeout``
     - Per-host DNS resolution timeout in seconds
     - ``3.0``
   * - ``--connect-timeout``
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     - Read timeout (seconds)
     - ``10.0``
   * - ``--no-bruteforce``
     - Skip DNS brute-force entirely, use CT logs only
     - ``False``

**Examples:**

.. code-block:: bash

   # Discover subdomains using CT logs + built-in wordlist
   nadzoring security subdomains example.com

   # CT logs only — no brute-force DNS
   nadzoring security subdomains --no-bruteforce example.com

   # Use a custom wordlist file
   nadzoring security subdomains --wordlist /path/to/subdomains.txt example.com

   # Increase concurrency and timeout for faster / more thorough scanning
   nadzoring security subdomains --threads 50 --connect-timeout 5 example.com

   # Export results as JSON
   nadzoring security subdomains -o json --save subdomains.json example.com

   # Quiet mode for scripting
   nadzoring security subdomains --quiet example.com

----

security watch-ssl
~~~~~~~~~~~~~~~~~~

Continuously monitor SSL/TLS certificates for one or more domains. On each check cycle the certificate is re-fetched and alerts are fired for: near-expiry (``status == warning``), expired certificates, certificate changes (expiry date difference between consecutive checks), and check failures. Runs indefinitely until Ctrl-C or for a fixed number of cycles.

.. code-block:: bash

   nadzoring security watch-ssl [OPTIONS] DOMAINS...

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--interval``
     - ``-i``
     - Seconds between full check cycles
     - ``3600``
   * - ``--cycles``
     - ``-c``
     - Number of cycles to run (``0`` = run indefinitely)
     - ``0``
   * - ``--days-before``
     - ``-d``
     - Days before expiry to trigger a warning alert
     - ``7``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Alert events fired:**

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Trigger
     - Message example
   * - Check failure
     - ``Check failed: [Errno 111] Connection refused``
   * - Expired certificate
     - ``Certificate has EXPIRED``
   * - Near expiry
     - ``Certificate expires in 5 day(s)``
   * - Certificate changed
     - ``Certificate changed: expiry 2025-06-01 → 2025-12-01``

**Examples:**

.. code-block:: bash

   # Monitor ya.ru indefinitely, check every hour
   nadzoring security watch-ssl ya.ru

   # Monitor multiple domains with a 14-day warning threshold
   nadzoring security watch-ssl --days-before 14 example.com github.com cloudflare.com

   # Run exactly 5 check cycles with a 60-second interval (useful for CI/testing)
   nadzoring security watch-ssl --cycles 5 --interval 60 example.com

   # Frequent checks — every 5 minutes — for a critical service
   nadzoring security watch-ssl --interval 300 api.example.com

   # Save all check results as JSON after monitoring ends
   nadzoring security watch-ssl --cycles 3 -o json --save ssl_history.json example.com

   # Quiet mode — suppress progress output, emit only alert lines
   nadzoring security watch-ssl --quiet --cycles 10 --interval 30 example.com

----

ARP Commands
------------

arp cache
~~~~~~~~~

Show the current ARP cache table (IP-to-MAC mappings).

.. code-block:: bash

   nadzoring arp cache [OPTIONS]

**Examples:**

.. code-block:: bash

   nadzoring arp cache
   nadzoring arp cache -o csv --save arp_cache.csv
   nadzoring arp cache -o json

----

arp detect-spoofing
~~~~~~~~~~~~~~~~~~~

Statically detect ARP spoofing by analyzing the current ARP cache.

.. code-block:: bash

   nadzoring arp detect-spoofing [OPTIONS] [INTERFACES]...

**Detects:** duplicate MAC across IPs (``duplicate_mac``) and duplicate IP with multiple MACs (``duplicate_ip``).

**Examples:**

.. code-block:: bash

   nadzoring arp detect-spoofing
   nadzoring arp detect-spoofing eth0 wlan0
   nadzoring arp detect-spoofing -o json --save spoofing_alerts.json

----

arp monitor-spoofing
~~~~~~~~~~~~~~~~~~~~

Monitor live network traffic for ARP spoofing in real time (requires root/admin).

.. code-block:: bash

   nadzoring arp monitor-spoofing [OPTIONS]

**Options:**

.. list-table::
   :header-rows: 1
   :widths: 20 10 60 10

   * - Option
     - Short
     - Description
     - Default
   * - ``--interface``
     - ``-i``
     - Interface to monitor
     - All
   * - ``--count``
     - ``-c``
     - Packets to capture
     - ``10``
   * - ``--timeout``
     - ``-t``
     - Capture timeout (seconds) — sets lifetime timeout
     - ``30``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds)
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds)
     - ``10.0``

**Examples:**

.. code-block:: bash

   nadzoring arp monitor-spoofing
   nadzoring arp monitor-spoofing --interface eth0 --count 200 --timeout 60
   nadzoring arp monitor-spoofing -o json --save arp_alerts.json

----

Output Formats
--------------

Use ``-o`` / ``--output`` to change the output format:

.. list-table::
   :header-rows: 1
   :widths: 20 80

   * - Format
     - Description
   * - ``table``
     - Rich terminal table (default)
   * - ``json``
     - JSON array, suitable for scripting
   * - ``csv``
     - Comma-separated values
   * - ``html``
     - Complete HTML page with CSS
   * - ``html_table``
     - HTML table fragment only
   * - ``yaml``
     - YAML format

**Examples:**

.. code-block:: bash

   nadzoring dns resolve -o json example.com
   nadzoring dns health -o html --save health.html example.com
   nadzoring network-base connections -o csv --save conns.csv
   nadzoring security check-ssl -o json example.com
   nadzoring security check-headers -o json --save headers.json https://example.com
   nadzoring security check-email -o json --save email_audit.json example.com
   nadzoring security subdomains -o json --save subdomains.json example.com

----

Saving Results
--------------

Use ``--save`` to write output to a file:

.. code-block:: bash

   nadzoring dns check -o html --save dns_report.html example.com
   nadzoring dns compare -o csv --save comparison.csv google.com
   nadzoring dns poisoning -o json --save poisoning.json example.com
   nadzoring network-base port-scan -o json --save scan.json example.com
   nadzoring network-base domain-info -o json --save domain_info.json example.com
   nadzoring security check-ssl -o json --save ssl_report.json example.com
   nadzoring security check-headers -o json --save headers_report.json https://example.com
   nadzoring security check-email -o json --save email_security.json example.com
   nadzoring security subdomains -o json --save subdomains.json example.com
   nadzoring arp cache -o csv --save arp.csv

----

Logging Levels
--------------

.. list-table::
   :header-rows: 1
   :widths: 20 20 60

   * - Mode
     - Flag
     - Behaviour
   * - Normal
     - (none)
     - Warnings + progress bars
   * - Verbose
     - ``--verbose``
     - Debug logs + execution timing
   * - Quiet
     - ``--quiet``
     - Results only — ideal for scripting

----

Timeout Configuration
---------------------

Nadzoring provides three timeout options that work together:

.. list-table::
   :header-rows: 1
   :widths: 30 60 10 10

   * - Option
     - Description
     - Default
     - Fallback
   * - ``--timeout``
     - Lifetime timeout for the entire operation
     - ``30.0``
     - —
   * - ``--connect-timeout``
     - Timeout for establishing connections
     - ``5.0``
     - Falls back to ``--timeout``
   * - ``--read-timeout``
     - Timeout for read operations after connection
     - ``10.0``
     - Falls back to ``--timeout``

**Resolution order per phase:**
1. Phase-specific option (``--connect-timeout`` / ``--read-timeout``)
2. Generic ``--timeout``
3. Module default (shown above)

**Example:**

.. code-block:: bash

   # All three phases have explicit timeouts
   nadzoring dns resolve --timeout 60 --connect-timeout 5 --read-timeout 30 example.com

   # Connect timeout inherits from generic timeout (30s), read uses default (10s)
   nadzoring dns resolve --timeout 30 example.com

   # Connect timeout = 3s, read timeout = 3s (both inherit from --timeout)
   nadzoring dns resolve --timeout 3 example.com

----

Error Handling
--------------

Every public Python API function follows a consistent error contract — functions never raise on expected DNS or network failures. All errors are returned as structured data so that scripts can handle them uniformly.

**DNS result-dict pattern** — check ``result["error"]`` before using ``result["records"]``:

.. code-block:: python

   from nadzoring.dns_lookup.utils import resolve_with_timer

   result = resolve_with_timer("example.com", "A")
   if result["error"]:
       # "Domain does not exist"  — NXDOMAIN
       # "No A records"           — record type not present
       # "Query timeout"          — nameserver did not respond
       print("DNS error:", result["error"])
   else:
       print(result["records"])
       print(f"RTT: {result['response_time']} ms")

**Return-None / empty-dict pattern** — used where a result cannot be partially valid:

.. code-block:: python

   from nadzoring.network_base.geolocation_ip import geo_ip

   result = geo_ip("8.8.8.8")
   if not result:
       print("Geolocation unavailable")
   else:
       print(f"{result['city']}, {result['country']}")

**Timeout exceptions** — raised only when lifetime timeout is exceeded:

.. code-block:: python

   from nadzoring.utils.timeout import OperationTimeoutError, timeout_context, TimeoutConfig

   config = TimeoutConfig(lifetime=5.0)
   try:
       with timeout_context(config):
           result = resolve_with_timer("example.com", "A")
   except OperationTimeoutError:
       print("Operation exceeded 5 second lifetime limit")

**Exception pattern** — used only for system-level failures (missing commands, unsupported OS):

.. code-block:: python

   from nadzoring.arp.cache import ARPCache, ARPCacheRetrievalError

   try:
       cache = ARPCache()
       entries = cache.get_cache()
   except ARPCacheRetrievalError as exc:
       print("Cannot read ARP cache:", exc)

All library exceptions inherit from ``nadzoring.utils.errors.NadzoringError`` and can be caught at any granularity:

.. code-block:: python

   from nadzoring.utils.errors import NadzoringError, DNSError, NetworkError, ARPError


## Source: docs/source/api_examples.rst

===========
Python API Examples
===========

This page provides practical Python API examples for all Nadzoring modules.

----

DNS Lookup API
--------------

.. code-block:: python

   from nadzoring.dns_lookup.utils import resolve_with_timer, get_public_dns_servers
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=2.0, read=8.0)

   # Resolve any record type
   result = resolve_with_timer("example.com", "MX", include_ttl=True, timeout_config=config)
   if result["error"]:
       print("Error:", result["error"])
   else:
       print(result["records"])  # ['10 mail.example.com']
       print(result["ttl"])  # 3600
       print(result["response_time"])  # 45.2

   # List built-in public servers
   servers = get_public_dns_servers()  # ['8.8.8.8', '1.1.1.1', ...]

----

Reverse DNS API
---------------

.. code-block:: python

   from nadzoring.dns_lookup.reverse import reverse_dns
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=2.0, read=5.0)

   # Standard reverse lookup
   result = reverse_dns("8.8.8.8", timeout_config=config)
   if result["error"]:
       # Possible values: 'No PTR record', 'No reverse DNS',
       # 'Query timeout', 'Invalid IP address: ...'
       print("Failed:", result["error"])
   else:
       print(result["hostname"])  # 'dns.google'

   # With a custom nameserver
   result = reverse_dns("1.1.1.1", nameserver="8.8.8.8")
   print(result["hostname"])  # 'one.one.one.one'

   # Compact error-safe pattern
   hostname = result["hostname"] or f"[{result['error']}]"

----

Network Base API
----------------

.. code-block:: python

   from nadzoring.network_base.ping_address import ping_addr
   from nadzoring.network_base.http_ping import http_ping
   from nadzoring.network_base.geolocation_ip import geo_ip
   from nadzoring.network_base.traceroute import traceroute
   from nadzoring.network_base.connections import get_connections
   from nadzoring.network_base.route_table import get_route_table
   from nadzoring.network_base.network_params import network_param
   from nadzoring.network_base.whois_lookup import whois_lookup
   from nadzoring.network_base.domain_info import get_domain_info
   from nadzoring.network_base.port_scanner import ScanConfig, scan_ports
   from nadzoring.network_base.service_detector import detect_service_on_host
   from nadzoring.network_base.parse_url import parse_url
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=2.0, read=8.0, lifetime=30.0)

   # Ping — returns bool
   alive = ping_addr("8.8.8.8")

   # HTTP probe — check .error before reading timing fields
   r = http_ping("https://example.com", timeout_config=config)
   if not r.error:
       print(r.ttfb_ms, r.status_code)

   # URL parsing
   parsed = parse_url("https://example.com/path?q=1")
   print(parsed["hostname"], parsed["path"])

   # Geolocation — returns {} on failure
   loc = geo_ip("8.8.8.8")
   if loc:
       print(loc["country"], loc["city"])

   # Comprehensive domain info — WHOIS + DNS + geo + reverse DNS
   info = get_domain_info("example.com")
   print(info["whois"]["registrar"])
   print(info["dns"]["ipv4"])
   print(info["geolocation"]["country"])
   print(info["reverse_dns"])

   # Traceroute
   for hop in traceroute("8.8.8.8", max_hops=10, per_hop_timeout=config.connect):
       print(hop.hop, hop.ip, hop.rtt_ms)

   # Active connections
   for conn in get_connections(protocol="tcp", state_filter="ESTABLISHED"):
       print(conn.local_address, "->", conn.remote_address)

   # Port scan
   scan_config = ScanConfig(targets=["example.com"], mode="fast", timeout_config=config)
   for result in scan_ports(scan_config):
       print("Open ports:", result.open_ports)

   # Service detection on a specific port
   service = detect_service_on_host("example.com", 80, timeout_config=config)
   print(service.detected_service or service.guessed_service)

----

Security API
------------

.. code-block:: python

   from nadzoring.security.check_website_ssl_cert import (
       check_ssl_certificate,
       check_ssl_expiry,
       check_ssl_expiry_with_fallback,
   )
   from nadzoring.security.http_headers import check_http_security_headers
   from nadzoring.security.email_security import check_email_security
   from nadzoring.security.subdomain_scan import scan_subdomains
   from nadzoring.security.ssl_monitor import SSLMonitor
   from nadzoring.utils.timeout import TimeoutConfig

   config = TimeoutConfig(connect=3.0, read=10.0)

   # SSL/TLS certificate check
   result = check_ssl_certificate("example.com", days_before=14, timeout_config=config)
   print(result["status"], result["remaining_days"])
   print(result["protocols"]["supported"])  # ['TLSv1.2', 'TLSv1.3']
   print(result["public_key"]["strength"])  # 'good'

   # Fallback mode for self-signed / problematic certs
   result = check_ssl_expiry_with_fallback("self-signed.example.com")

   # HTTP security header audit
   headers = check_http_security_headers("https://example.com", timeout_config=config)
   print(headers["score"])  # 0–100
   print(headers["missing"])  # list of absent recommended headers
   print(headers["leaking"])  # {'Server': 'nginx/1.18.0'}

   # Email security (SPF / DKIM / DMARC)
   email = check_email_security("example.com")
   print(email["overall_score"])  # 0–3
   print(email["spf"]["all_qualifier"])  # '~' (softfail)
   print(email["dmarc"]["policy"])  # 'reject'
   print(email["all_issues"])  # aggregated issue list

   # Subdomain discovery
   subdomains = scan_subdomains(
       "example.com",
       max_threads=30,
       timeout_config=config,
   )
   for s in subdomains:
       print(s["subdomain"], s["ip"], s["source"])

   # Continuous SSL monitoring
   monitor = SSLMonitor(["example.com", "github.com"], interval=3600, days_before=14, timeout_config=config)
   monitor.set_alert_callback(lambda domain, msg: print(f"ALERT {domain}: {msg}"))
   results = monitor.run_cycles(cycles=3)
   for r in monitor.history():
       print(r["domain"], r["status"], r["remaining_days"])

----

ARP API
-------

.. code-block:: python

   from nadzoring.arp.cache import ARPCache, ARPCacheRetrievalError
   from nadzoring.arp.detector import ARPSpoofingDetector
   from nadzoring.arp.realtime import ARPRealtimeDetector
   from nadzoring.utils.timeout import TimeoutConfig

   # ARP cache — raises ARPCacheRetrievalError on system failure
   try:
       cache = ARPCache()
       for entry in cache.get_cache():
           print(entry.ip_address, entry.mac_address, entry.state.value)
   except ARPCacheRetrievalError as exc:
       print("ARP cache unavailable:", exc)

   # Static spoofing detection
   detector = ARPSpoofingDetector(cache)
   for alert in detector.detect():
       print(alert.alert_type, alert.description)

   # Real-time monitoring with timeouts
   config = TimeoutConfig(connect=2.0, read=8.0, lifetime=45.0)
   rt = ARPRealtimeDetector()
   alerts = rt.monitor(interface="eth0", count=50, timeout_config=config)
   print(rt.get_stats())


## Source: docs/source/code_examples.rst

===============
Code Examples
===============

Practical examples for common use cases.

----

DNS Diagnostics
---------------

.. code-block:: bash

   nadzoring dns health example.com
   nadzoring dns trace example.com
   nadzoring dns compare -t A -t MX example.com
   nadzoring dns check -t ALL -v example.com

----

Reverse DNS Batch Lookup
------------------------

.. code-block:: bash

   # Look up multiple IPs at once
   nadzoring dns reverse 8.8.8.8 1.1.1.1 9.9.9.9 208.67.222.222

   # Save results
   nadzoring dns reverse -o json --save ptr_records.json 8.8.8.8 1.1.1.1

----

DNS Poisoning Detection
-----------------------

.. code-block:: bash

   nadzoring dns poisoning -v twitter.com
   nadzoring dns poisoning -c 8.8.8.8 -c 1.1.1.1 example.com
   nadzoring dns poisoning -o html --save poisoning_report.html github.com

----

DNS Performance Benchmarking
----------------------------

.. code-block:: bash

   nadzoring dns benchmark --queries 20 --parallel
   nadzoring dns benchmark -s 8.8.8.8 -s 1.1.1.1 -s 208.67.222.222 -s 9.9.9.9
   nadzoring dns benchmark -t MX -d gmail.com --queries 15

----

Port Scanning
-------------

.. code-block:: bash

   nadzoring network-base port-scan --mode full --protocol tcp example.com
   nadzoring network-base port-scan --mode custom --ports 20-1024 example.com
   nadzoring network-base port-scan -o csv --save network_scan.csv 192.168.1.1

----

HTTP Service Probing
--------------------

.. code-block:: bash

   nadzoring network-base http-ping --show-headers https://api.example.com/health
   nadzoring network-base http-ping https://google.com https://cloudflare.com https://github.com
   nadzoring network-base http-ping -o csv --save http_metrics.csv https://example.com

----

SSL/TLS Certificate Auditing
----------------------------

.. code-block:: bash

   # Quick check — compact summary
   nadzoring security check-ssl example.com

   # Check multiple domains with a 30-day warning window
   nadzoring security check-ssl --days-before 30 google.com github.com cloudflare.com ya.ru

   # Full details including SAN list, protocol versions, chain info
   nadzoring security check-ssl --full example.com

   # Check without verifying the chain (self-signed / internal CA)
   nadzoring security check-ssl --no-verify https://internal.corp.example.com

   # Save full report as JSON
   nadzoring security check-ssl --full -o json --save ssl_audit.json example.com github.com

----

HTTP Security Header Auditing
-----------------------------

.. code-block:: bash

   # Single URL
   nadzoring security check-headers https://example.com

   # Batch audit of several services
   nadzoring security check-headers \
       https://api.example.com \
       https://admin.example.com \
       https://static.example.com

   # Skip SSL verification for internal endpoints
   nadzoring security check-headers --no-verify https://internal.corp.example.com

   # Export as JSON for CI / dashboard integration
   nadzoring security check-headers -o json --save headers_audit.json https://example.com

----

Email Security Validation
-------------------------

.. code-block:: bash

   # Check a single domain
   nadzoring security check-email example.com

   # Audit multiple domains
   nadzoring security check-email gmail.com outlook.com yahoo.com proton.me

   # Export full JSON report with SPF/DKIM/DMARC details
   nadzoring security check-email -o json --save email_audit.json example.com

   # Check all your owned domains at once
   nadzoring security check-email corp.example.com mail.example.com newsletter.example.com

----

Subdomain Discovery
-------------------

.. code-block:: bash

   # CT logs + built-in wordlist brute-force
   nadzoring security subdomains example.com

   # CT logs only — faster, no DNS brute-force
   nadzoring security subdomains --no-bruteforce example.com

   # Custom wordlist and more threads for deeper scanning
   nadzoring security subdomains \
       --wordlist /path/to/big-wordlist.txt \
       --threads 100 \
       --connect-timeout 5 \
       example.com

   # Save discovered subdomains as JSON
   nadzoring security subdomains -o json --save subdomains.json example.com

----

Continuous SSL Monitoring
-------------------------

.. code-block:: bash

   # Monitor a single domain indefinitely (Ctrl-C to stop)
   nadzoring security watch-ssl example.com

   # Monitor multiple domains with a 14-day warning threshold
   nadzoring security watch-ssl --days-before 14 \
       example.com github.com cloudflare.com api.example.com

   # Check every 5 minutes for a critical service
   nadzoring security watch-ssl --interval 300 api.example.com

   # Run 10 cycles with a 60-second interval and save all results
   nadzoring security watch-ssl --cycles 10 --interval 60 \
       -o json --save ssl_monitor_history.json example.com

----

ARP Spoofing Detection
----------------------

.. code-block:: bash

   nadzoring arp detect-spoofing eth0
   nadzoring arp monitor-spoofing --interface eth0 --timeout 60
   nadzoring arp monitor-spoofing -o json --save arp_alerts.json

----

Network Path Analysis
---------------------

.. code-block:: bash

   nadzoring network-base traceroute --max-hops 30 github.com
   nadzoring network-base traceroute google.com cloudflare.com amazon.com
   nadzoring network-base route
   nadzoring network-base connections --state LISTEN

----

Complete Network Diagnostics
----------------------------

.. code-block:: bash

   nadzoring network-base params -v
   nadzoring network-base host-to-ip google.com cloudflare.com github.com
   nadzoring network-base ping 8.8.8.8 1.1.1.1 google.com
   nadzoring network-base geolocation 8.8.8.8 1.1.1.1
   nadzoring network-base domain-info example.com
   nadzoring network-base port-scan --mode fast example.com
   nadzoring network-base traceroute cloudflare.com
   nadzoring security check-ssl example.com
   nadzoring security check-headers https://example.com
   nadzoring security check-email example.com
   nadzoring arp cache

----

Automated DNS Server Monitoring
-------------------------------

This section covers three integration approaches for continuous monitoring:
a **shell script** for use with cron/systemd, a **Python script** for
in-process loops with alerting, and **scheduling setup** for both Linux and Windows.

**Shell script with alerting thresholds**

Save as ``dns_monitor.sh`` and make executable (``chmod +x dns_monitor.sh``):

.. code-block:: bash

   #!/bin/bash
   # dns_monitor.sh — continuous DNS health and performance monitor
   # Designed to be called by cron or systemd timer.

   set -euo pipefail

   # ── Configuration ────────────────────────────────────────────────────────────
   TARGET_DOMAIN="${1:-example.com}"
   DNS_SERVER="${2:-8.8.8.8}"
   REPORT_DIR="${DNS_MONITOR_DIR:-/var/log/nadzoring}"
   ALERT_EMAIL="${DNS_ALERT_EMAIL:-}"        # leave empty to disable email alerts
   HEALTH_THRESHOLD=70                       # score below this triggers an alert
   BENCHMARK_QUERIES=5                       # queries per server for each run
   CONNECT_TIMEOUT="${DNS_CONNECT_TIMEOUT:-5}"
   READ_TIMEOUT="${DNS_READ_TIMEOUT:-10}"
   LIFETIME_TIMEOUT="${DNS_LIFETIME_TIMEOUT:-30}"

   # ── Setup ────────────────────────────────────────────────────────────────────
   mkdir -p "$REPORT_DIR"
   TIMESTAMP=$(date +%Y%m%d_%H%M%S)
   LOG_FILE="$REPORT_DIR/monitor_${TIMESTAMP}.log"
   SUMMARY_FILE="$REPORT_DIR/summary.jsonl"  # append-only JSONL for trend analysis

   log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }
   alert() {
       log "ALERT: $*"
       if [[ -n "$ALERT_EMAIL" ]]; then
           echo "$*" | mail -s "[nadzoring] DNS alert: $TARGET_DOMAIN" "$ALERT_EMAIL" || true
       fi
   }

   # ── DNS Health Check ─────────────────────────────────────────────────────────
   log "Starting DNS health check for $TARGET_DOMAIN via $DNS_SERVER"

   HEALTH_JSON="$REPORT_DIR/health_${TIMESTAMP}.json"
   if nadzoring dns health -n "$DNS_SERVER" -o json --quiet \
           --connect-timeout "$CONNECT_TIMEOUT" \
           --read-timeout "$READ_TIMEOUT" \
           --timeout "$LIFETIME_TIMEOUT" \
           --save "$HEALTH_JSON" "$TARGET_DOMAIN"; then
       SCORE=$(python3 -c "import json,sys; d=json.load(open('$HEALTH_JSON')); print(d.get('score',0))" 2>/dev/null || echo 0)
       STATUS=$(python3 -c "import json,sys; d=json.load(open('$HEALTH_JSON')); print(d.get('status','unknown'))" 2>/dev/null || echo unknown)
       log "Health score: $SCORE ($STATUS)"

       if [[ "$SCORE" -lt "$HEALTH_THRESHOLD" ]]; then
           alert "Health score $SCORE is below threshold $HEALTH_THRESHOLD (status: $STATUS) for $TARGET_DOMAIN"
       fi
   else
       alert "dns health check command failed for $TARGET_DOMAIN"
       SCORE=0; STATUS="error"
   fi

   # ── DNS Benchmark ────────────────────────────────────────────────────────────
   BENCH_JSON="$REPORT_DIR/benchmark_${TIMESTAMP}.json"
   if nadzoring dns benchmark -s "$DNS_SERVER" -s 8.8.8.8 -s 1.1.1.1 \
           -d "$TARGET_DOMAIN" -q "$BENCHMARK_QUERIES" \
           --connect-timeout "$CONNECT_TIMEOUT" \
           --read-timeout "$READ_TIMEOUT" \
           --timeout "$LIFETIME_TIMEOUT" \
           -o json --quiet --save "$BENCH_JSON"; then
       AVG_MS=$(python3 -c "
   import json
   data = json.load(open('$BENCH_JSON'))
   target = next((r for r in data if r['server'] == '$DNS_SERVER'), None)
   print(round(target['avg_response_time'], 1) if target else 'N/A')
   " 2>/dev/null || echo "N/A")
       log "Benchmark avg response time for $DNS_SERVER: ${AVG_MS}ms"
   else
       log "WARNING: benchmark failed"
       AVG_MS="N/A"
   fi

   # ── DNS Compare (discrepancy detection) ─────────────────────────────────────
   COMPARE_JSON="$REPORT_DIR/compare_${TIMESTAMP}.json"
   nadzoring dns compare -t A -t MX \
       -s "$DNS_SERVER" -s 8.8.8.8 -s 1.1.1.1 \
       -o json --quiet --save "$COMPARE_JSON" "$TARGET_DOMAIN" || true

   DIFFS=$(python3 -c "
   import json
   data = json.load(open('$COMPARE_JSON'))
   diffs = data.get('differences', [])
   print(len(diffs))
   " 2>/dev/null || echo 0)

   if [[ "$DIFFS" -gt 0 ]]; then
       alert "$DIFFS DNS discrepancies detected for $TARGET_DOMAIN — possible poisoning or misconfiguration"
   fi
   log "DNS compare: $DIFFS discrepancies found"

   # ── Reverse DNS Spot-check ───────────────────────────────────────────────────
   RESOLVED_IP=$(nadzoring network-base host-to-ip --quiet -o json "$TARGET_DOMAIN" 2>/dev/null \
       | python3 -c "import json,sys; d=json.load(sys.stdin); print(d[0].get('ip','') if d else '')" 2>/dev/null || echo "")

   REVERSE_HOST="N/A"
   if [[ -n "$RESOLVED_IP" ]]; then
       REVERSE_JSON="$REPORT_DIR/reverse_${TIMESTAMP}.json"
       nadzoring dns reverse -n "$DNS_SERVER" -o json --quiet \
           --connect-timeout "$CONNECT_TIMEOUT" \
           --read-timeout "$READ_TIMEOUT" \
           --save "$REVERSE_JSON" "$RESOLVED_IP" || true
       REVERSE_HOST=$(python3 -c "
   import json
   data = json.load(open('$REVERSE_JSON'))
   print(data[0].get('hostname','N/A') if data else 'N/A')
   " 2>/dev/null || echo "N/A")
       log "Reverse DNS for $RESOLVED_IP → $REVERSE_HOST"
   fi

   # ── Append to JSONL summary for trend analysis ───────────────────────────────
   python3 - <<EOF >> "$SUMMARY_FILE"
   import json, datetime
   print(json.dumps({
       "timestamp": "$TIMESTAMP",
       "domain": "$TARGET_DOMAIN",
       "dns_server": "$DNS_SERVER",
       "health_score": $SCORE,
       "health_status": "$STATUS",
       "avg_response_ms": "$AVG_MS",
       "discrepancies": $DIFFS,
       "resolved_ip": "$RESOLVED_IP",
       "reverse_host": "$REVERSE_HOST",
   }))
   EOF

   log "Run complete. Reports saved to $REPORT_DIR"

**Scheduling with cron (Linux/macOS)**

.. code-block:: bash

   # Edit crontab
   crontab -e

   # Run every 5 minutes
   */5 * * * * /path/to/dns_monitor.sh example.com 8.8.8.8

   # Run every hour with email alerts
   0 * * * * DNS_ALERT_EMAIL=ops@example.com /path/to/dns_monitor.sh example.com 8.8.8.8

   # Run every 15 minutes, logging cron output
   */15 * * * * /path/to/dns_monitor.sh example.com 8.8.8.8 >> /var/log/nadzoring/cron.log 2>&1

**Scheduling with systemd timer (Linux, recommended)**

Create ``/etc/systemd/system/nadzoring-dns-monitor.service``:

.. code-block:: ini

   [Unit]
   Description=Nadzoring DNS health monitor
   After=network-online.target
   Wants=network-online.target

   [Service]
   Type=oneshot
   ExecStart=/path/to/dns_monitor.sh example.com 8.8.8.8
   Environment=DNS_MONITOR_DIR=/var/log/nadzoring
   Environment=DNS_ALERT_EMAIL=ops@example.com
   Environment=DNS_CONNECT_TIMEOUT=5
   Environment=DNS_READ_TIMEOUT=10
   Environment=DNS_LIFETIME_TIMEOUT=30
   StandardOutput=journal
   StandardError=journal

Create ``/etc/systemd/system/nadzoring-dns-monitor.timer``:

.. code-block:: ini

   [Unit]
   Description=Run Nadzoring DNS monitor every 5 minutes

   [Timer]
   OnBootSec=60
   OnUnitActiveSec=5min
   Persistent=true

   [Install]
   WantedBy=timers.target

Enable and start:

.. code-block:: bash

   sudo systemctl daemon-reload
   sudo systemctl enable --now nadzoring-dns-monitor.timer
   sudo systemctl status nadzoring-dns-monitor.timer
   journalctl -u nadzoring-dns-monitor.service -f   # follow live logs

**Python continuous monitoring loop (in-process)**

Use ``DNSMonitor`` directly for in-process monitoring with custom alerting:

*Infinite loop (blocks until Ctrl-C or SIGTERM):*

.. code-block:: python

   from nadzoring.dns_lookup.monitor import AlertEvent, DNSMonitor, MonitorConfig
   from nadzoring.utils.timeout import TimeoutConfig

   timeout_config = TimeoutConfig(connect=3.0, read=10.0, lifetime=30.0)


   def send_alert(alert: AlertEvent) -> None:
       print(f"ALERT [{alert.alert_type}]: {alert.message}")


   config = MonitorConfig(
       domain="example.com",
       nameservers=["8.8.8.8", "1.1.1.1"],
       interval=60.0,
       max_response_time_ms=500.0,
       min_success_rate=0.95,
       log_file="dns_monitor.jsonl",
       alert_callback=send_alert,
       timeout_config=timeout_config,
   )

   monitor = DNSMonitor(config)
   monitor.run()
   print(monitor.report())

*Finite cycles (CI pipelines, cron scripts):*

.. code-block:: python

   from nadzoring.dns_lookup.monitor import DNSMonitor, MonitorConfig
   from nadzoring.utils.timeout import TimeoutConfig
   from statistics import mean

   timeout_config = TimeoutConfig(connect=2.0, read=8.0)

   config = MonitorConfig(
       domain="example.com",
       nameservers=["8.8.8.8", "1.1.1.1"],
       interval=10.0,
       run_health_check=False,
       timeout_config=timeout_config,
   )
   monitor = DNSMonitor(config)
   history = monitor.run_cycles(6)

   rts = [s.avg_response_time_ms for c in history for s in c.samples if s.avg_response_time_ms is not None]
   print(f"Mean RT: {mean(rts):.1f}ms")
   print(monitor.report())

*Analyse saved log:*

.. code-block:: python

   from nadzoring.dns_lookup.monitor import load_log
   from statistics import mean

   cycles = load_log("dns_monitor.jsonl")
   rts = [s["avg_response_time_ms"] for c in cycles for s in c["samples"] if s["avg_response_time_ms"] is not None]
   alerts = [a for c in cycles for a in c.get("alerts", [])]
   print(f"Cycles: {len(cycles)}  Mean RT: {mean(rts):.1f}ms  Alerts: {len(alerts)}")

----

Quick Website Block Check
-------------------------

.. code-block:: bash

   nadzoring dns resolve -t ALL example.com
   nadzoring dns reverse 93.184.216.34
   nadzoring dns trace example.com
   nadzoring network-base ping example.com
   nadzoring dns compare example.com
   nadzoring dns poisoning example.com
   nadzoring network-base http-ping https://example.com
   nadzoring network-base traceroute example.com
   nadzoring security check-ssl example.com
   nadzoring security check-headers https://example.com
   nadzoring security check-email example.com
   nadzoring security subdomains example.com


## Source: docs/source/architecture.rst

Architecture
============

Nadzoring is structured in concentric layers following the principles of
**Clean Architecture**, **Single Responsibility (SRP)**, **DRY**, and
**KISS**.  This page explains the layout so that contributors and
integrators know where each concern lives.

----

Package Layout
--------------

.. code-block:: text

   src/nadzoring/
   ├── cli.py                    # Entry-point: registers command groups
   ├── __main__.py               # python -m nadzoring
   │
   ├── commands/                 # CLI layer — Click command groups
   │   ├── dns_commands.py       #   dns group
   │   ├── network_commands.py   #   network-base group
   │   ├── security_commands.py  #   security group
   │   └── arp_commands.py       #   arp group
   │
   ├── dns_lookup/               # Domain layer — DNS
   │
   ├── network_base/             # Domain layer — network diagnostics
   │
   ├── security/                 # Domain layer — security auditing
   │
   ├── arp/                      # Domain layer — ARP security
   │
   ├── plugins/                  # Connector framework (non-CLI integrations)
   │
   └── utils/                    # Cross-cutting utilities
       ├── errors.py             #   Exception hierarchy
       ├── validators.py         #   Input validation functions
       ├── formatters.py         #   Output formatting (table/json/csv/html)
       └── decorators.py         #   @common_cli_options decorator

----

Layer Responsibilities
-----------------------

**CLI layer** (``commands/``)
    Owns *only* Click option parsing, progress bars, and output dispatch.
    Must not contain business logic.  Calls domain-layer functions and
    passes results to formatters.

**Domain layer** (``dns_lookup/``, ``network_base/``, ``security/``, ``arp/``)
    Contains all business logic.  Modules are scoped to a single concern
    (SRP).  Functions return typed dicts or dataclasses; they never print
    or call Click.

**Integrations** (``plugins/``)
    Optional connector classes for Python embedders (monitoring, tests).
    They wrap domain functions and return :class:`nadzoring.plugins.result.ProbeResult`
    objects.  The stock CLI does not depend on this package.

**Cross-cutting** (``utils/``)
    Shared helpers with no dependency on domain modules.  ``errors.py``
    defines the exception hierarchy.  ``validators.py`` contains pure
    functions.  ``formatters.py`` knows only about Python built-ins.

----

Design Principles Applied
--------------------------

SRP — Single Responsibility Principle
    Each module owns exactly one concern.  ``validation.py`` validates
    records; ``health.py`` scores them; ``utils.py`` resolves queries.
    ``check_website_ssl_cert.py`` handles only SSL certificate inspection;
    ``http_headers.py`` handles only header analysis; ``email_security.py``
    handles only SPF/DKIM/DMARC.  Formatting lives in
    ``utils/formatters.py``, not in domain modules.

DRY — Don't Repeat Yourself
    - Empty result dicts are built by factory helpers (``_make_empty_result``,
      ``_make_result``).
    - Record extraction is dispatched through a ``_EXTRACTORS`` map instead
      of a long ``if/elif`` chain.
    - CLI options are injected via the ``@common_cli_options`` decorator.
    - DNS TXT record querying in ``email_security.py`` is abstracted behind
      ``_query_txt()``, which tries ``dnspython``, then ``dig``, then
      ``nslookup`` automatically.

KISS — Keep It Simple
    Complex operations (trace, poisoning detection, subdomain scanning) are
    broken into small private functions with a single clear name.  Public
    functions have one entry point with documented parameters and return
    values.

Error handling
    Domain functions never raise on expected failures (DNS errors, network
    timeouts, missing PTR records, SSL connection errors).  All failures are
    returned as structured data so that CLI and scripting callers can handle
    them uniformly.  Only truly unexpected errors (programming mistakes,
    missing system commands) are allowed to propagate as exceptions.

----

Data Flow
---------

.. code-block:: text

   User / Script
        │
        ▼
   CLI layer (commands/)
        │  Click parses args
        │
        ▼
   Domain layer (dns_lookup / network_base / security / arp)
        │  Business logic, structured results
        │
        ▼
   External systems
        │  dnspython, ping3, requests, scapy, ssl, socket,
        │  system commands (dig, nslookup, whois, traceroute)
        │
        ▼
   Results bubble back up
        │
        ▼
   utils/formatters.py
        │  table / json / csv / html
        │
        ▼
   stdout / file

----

Security Module Data Flow
--------------------------

The ``security/`` domain package follows the same pattern with additional
external dependencies:

.. code-block:: text

   nadzoring security check-ssl example.com
        │
        ▼
   security_commands.py          # parses --days-before, --full, --no-verify
        │
        ▼
   security/check_website_ssl_cert.py
        │  ssl.create_default_context()
        │  socket connection → TLS handshake → certificate parsing
        │  _probe_tls_version() per TLS version (TLSv1.0–TLSv1.3)
        │
        ▼
   Structured result dict → formatters.py → stdout / file

   nadzoring security check-email example.com
        │
        ▼
   security_commands.py
        │
        ▼
   security/email_security.py
        │  _query_txt() → dnspython | dig | nslookup
        │  _analyze_spf() / _analyze_dkim() / _analyze_dmarc()
        │
        ▼
   Structured result dict → formatters.py → stdout / file

   nadzoring security subdomains example.com
        │
        ▼
   security_commands.py
        │
        ▼
   security/subdomain_scan.py
        │  _fetch_ct_subdomains() → crt.sh HTTPS API
        │  ThreadPoolExecutor → _probe_subdomain() → socket.gethostbyname()
        │
        ▼
   List of result dicts → formatters.py → stdout / file

----

Adding a New Feature
--------------------

1. **Create a module** in the appropriate domain package (e.g.
   ``security/myfeature.py`` or ``dns_lookup/myfeature.py``).
2. **Define a public function** with a clear docstring, type hints, and
   error handling that returns structured data.
3. **Export it** from the package ``__init__.py``.
4. **Add a CLI command** in the relevant ``commands/`` file using
   ``@common_cli_options``.
5. **Add a formatter** in ``utils/formatters.py`` if needed.
6. **Write tests** in ``tests/``.
7. **Document it** in a new or existing ``.rst`` file under ``commands/``
   or the API reference.


## Source: docs/source/error_handling.rst

Error Handling
==============

Nadzoring follows a consistent error-handling pattern across all Python APIs:
functions **never raise exceptions for expected failures** (DNS errors,
network timeouts, missing PTR records, SSL connection errors). All such
failures are returned as structured data with type-safe error fields,
making the library safe to use in automation scripts without wrapping every
call in try/except.

Only truly unexpected errors (programming mistakes, missing system commands,
unsupported operating systems) are allowed to propagate as exceptions.

----

Type-Safe Error Fields
----------------------

All result dictionaries use ``Literal`` types for their ``"error"`` field,
defined in module-specific ``errors.py`` files. This enables:

- **IDE autocompletion** for error strings
- **Static type checking** (mypy catches typos)
- **Single source of truth** for documentation

.. code-block:: python

   from nadzoring.dns_lookup.utils import resolve_with_timer
   from nadzoring.dns_lookup.errors import DNSResolveError

   result = resolve_with_timer("example.com", "A")

   # Type-safe error checking
   if result["error"] == "Domain does not exist":
       handle_nxdomain()
   elif result["error"] == "Query timeout":
       retry_with_longer_timeout()

Error literal modules:

- ``nadzoring.dns_lookup.errors`` — DNS resolution, reverse DNS, trace
- ``nadzoring.security.errors`` — SSL certificates, HTTP headers, email security
- ``nadzoring.network_base.errors`` — ping, traceroute, WHOIS, port scanning
- ``nadzoring.arp.errors`` — ARP cache retrieval, spoofing detection

----

DNS Result Pattern
------------------

Functions that perform DNS lookups (``resolve_with_timer``, ``reverse_dns``)
return a dictionary with an ``"error"`` field typed as ``DNSResolveError | None``
or ``DNSReverseError | None``. Always check it before using other fields:

.. code-block:: python

   from nadzoring.dns_lookup.utils import resolve_with_timer
   from nadzoring.dns_lookup.errors import DNSResolveError

   result = resolve_with_timer("example.com", "A")

   if result["error"]:
       # Handle the error — result["error"] is type DNSResolveError
       print("DNS error:", result["error"])
   else:
       # Safe to use records and response_time
       print(result["records"])
       print(f"RTT: {result['response_time']} ms")

Possible error values for ``resolve_with_timer`` (see ``DNSResolveError``):

- ``"Domain does not exist"`` — NXDOMAIN response
- ``"No records of requested type"`` — domain exists but has no records of the requested type
- ``"Query timeout"`` — nameserver did not respond within the timeout
- ``"Operation exceeded lifetime timeout"`` — overall timeout exceeded
- ``"Resolver error"`` — unexpected resolver error

**Reverse DNS:**

.. code-block:: python

   from nadzoring.dns_lookup.reverse import reverse_dns
   from nadzoring.dns_lookup.errors import DNSReverseError

   result = reverse_dns("8.8.8.8")

   if result["error"]:
       # result["error"] is type DNSReverseError | None
       print("Reverse lookup failed:", result["error"])
       # Possible values: "No PTR record", "No reverse DNS",
       # "Query timeout", "Invalid IP address", "Resolver error"
   else:
       print(result["hostname"])

----

Result Handling Utilities
-------------------------

The ``nadzoring.utils.result`` module provides helper functions for working
with error-bearing result dictionaries:

.. code-block:: python

   from nadzoring.utils.result import is_success, unwrap, unwrap_or
   from nadzoring.utils.errors import NadzoringError

   result = resolve_with_timer("example.com", "A")

   # Check success without accessing error field
   if is_success(result):
       print(result["records"])

   # Raise on error
   try:
       safe_result = unwrap(result)
       print(safe_result["records"])
   except NadzoringError as e:
       print(f"Operation failed: {e}")

   # Provide fallback on error
   records = unwrap_or(result, [])
   # records is either the original result dict or empty list

----

Timeout Errors
--------------

The ``OperationTimeoutError`` exception is raised when a lifetime timeout is
exceeded. This is an **expected failure** — it should be caught and handled
by converting to an error field in the result dict, not allowed to propagate
to the user.

.. code-block:: python

   from nadzoring.utils.timeout import TimeoutConfig, timeout_context, OperationTimeoutError

   config = TimeoutConfig(lifetime=5.0)

   try:
       with timeout_context(config):
           result = long_running_operation()
   except OperationTimeoutError:
       result = {"error": "Operation exceeded lifetime timeout"}

**When to use:** Lifetime timeouts are useful for operations that may hang
indefinitely (e.g., DNS queries to unresponsive servers, socket connections
to firewalled hosts). Phase-specific timeouts (connect/read) are handled by
socket timeouts and do not raise ``OperationTimeoutError``.

**Platform differences:** On Unix systems, ``timeout_context`` uses SIGALRM
which can interrupt blocking system calls. On Windows, the timeout is checked
only after the operation completes (best-effort).

----

Empty-Result Pattern
--------------------

Some functions return an empty dict (or empty list) when the result cannot be
partially valid. This is common for geolocation, WHOIS, or system information
commands.

.. code-block:: python

   from nadzoring.network_base.geolocation_ip import geo_ip

   result = geo_ip("8.8.8.8")
   if not result:
       print("Geolocation unavailable (private IP, rate-limit, or network error)")
   else:
       print(result["city"], result["country"])

   from nadzoring.network_base.whois_lookup import whois_lookup
   from nadzoring.network_base.errors import WHOISError

   result = whois_lookup("example.com")
   if result.get("error"):
       # result["error"] is type WHOISError | None
       print("WHOIS lookup failed:", result["error"])
       # Possible values: "Command not found", "Query timeout",
       # "No information found", "Invalid target"

----

Security Module Error Types
---------------------------

**SSL/TLS Certificate Checks** (``nadzoring.security.errors.SSLCertError``):

.. code-block:: python

   from nadzoring.security.check_website_ssl_cert import check_ssl_certificate
   from nadzoring.security.errors import SSLCertError

   result = check_ssl_certificate("example.com")
   if result.get("error"):
       # Possible values: "Certificate expired", "Certificate not yet valid",
       # "Hostname mismatch", "Self-signed certificate", "Connection timeout",
       # "SSL handshake failed", "Certificate verification failed",
       # "No certificate returned"
       print("SSL error:", result["error"])

**HTTP Security Headers** (``nadzoring.security.errors.HTTPHeaderError``):

.. code-block:: python

   from nadzoring.security.http_headers import check_http_security_headers
   from nadzoring.security.errors import HTTPHeaderError

   result = check_http_security_headers("https://example.com")
   if result.get("error"):
       # Possible values: "Request timeout", "Connection refused",
       # "SSL verification failed", "Too many redirects", "Invalid URL"
       print("HTTP check failed:", result["error"])

**Email Security** (``nadzoring.security.errors.EmailSecurityError``):

.. code-block:: python

   from nadzoring.security.email_security import check_email_security
   from nadzoring.security.errors import EmailSecurityError

   result = check_email_security("example.com")
   # Errors are collected in result["all_issues"] list
   # Each issue is one of: "No SPF record", "No DKIM record",
   # "No DMARC record", "SPF lookup timeout", etc.

----

Network Base Module Error Types
-------------------------------

**WHOIS Lookups** (``nadzoring.network_base.errors.WHOISError``):

.. code-block:: python

   from nadzoring.network_base.whois_lookup import whois_lookup
   from nadzoring.network_base.errors import WHOISError

   result = whois_lookup("example.com")
   if result.get("error"):
       # Possible values: "Command not found", "Query timeout",
       # "No information found", "Invalid target"
       print("WHOIS error:", result["error"])

**Traceroute** (``nadzoring.network_base.errors.TracerouteError``):

.. code-block:: python

   from nadzoring.network_base.traceroute import traceroute
   from nadzoring.network_base.errors import TracerouteError

   # traceroute returns list of TraceHop objects, errors are logged
   # but the function may raise on system-level failures with messages:
   # "Permission denied (needs root)", "Command not found",
   # "Network unreachable", "DNS resolution failed", "Timeout"

**Port Scanning** (``nadzoring.network_base.errors.PortScanError``):

.. code-block:: python

   from nadzoring.network_base.port_scanner import scan_ports, ScanConfig
   from nadzoring.network_base.errors import PortScanError

   # scan_ports returns list of ScanResult, errors are logged internally
   # Resolution failures return None for target_ip and are skipped

**Geolocation** (``nadzoring.network_base.errors.GeolocationError``):

.. code-block:: python

   from nadzoring.network_base.geolocation_ip import geo_ip

   result = geo_ip("8.8.8.8")
   if not result:
       # Empty dict indicates: "API request failed", "Rate limit exceeded",
       # "Invalid IP address", or "Private IP address"
       print("Geolocation unavailable")

----

ARP Module Error Types
----------------------

**ARP Cache Retrieval** (``nadzoring.arp.errors.ARPCacheError``):

.. code-block:: python

   from nadzoring.arp.cache import ARPCache, ARPCacheRetrievalError
   from nadzoring.arp.errors import ARPCacheError

   try:
       cache = ARPCache()
       entries = cache.get_cache()
   except ARPCacheRetrievalError as e:
       # Exception message is one of: "Command not found",
       # "Permission denied (needs root)", "Unsupported platform",
       # "Failed to parse ARP cache output"
       print("ARP cache error:", e)

**ARP Spoofing Detection** (``nadzoring.arp.errors.ARPSpoofingError``):

.. code-block:: python

   from nadzoring.arp.realtime import ARPRealtimeDetector
   from nadzoring.arp.errors import ARPSpoofingError

   detector = ARPRealtimeDetector()
   try:
       alerts = detector.monitor(interface="eth0", count=100)
   except RuntimeError as e:
       # RuntimeError wraps ARPSpoofingError messages:
       # "No network interface specified", "Packet capture failed",
       # "No ARP packets captured"
       print("Monitoring failed:", e)

----

Exception Pattern
-----------------

Exceptions are reserved for system-level failures that the caller cannot
reasonably handle inline. All custom exceptions inherit from
``nadzoring.utils.errors.NadzoringError``.

.. code-block:: python

   from nadzoring.arp.cache import ARPCache, ARPCacheRetrievalError
   from nadzoring.utils.errors import ARPError, DNSError, NetworkError, NadzoringError

   try:
       cache = ARPCache()
       entries = cache.get_cache()
   except ARPCacheRetrievalError as exc:
       # System command missing, permission denied, etc.
       # Exception message matches ARPCacheError literal
       print("Cannot read ARP cache:", exc)

   # Catch any Nadzoring error at any granularity
   try:
       # some operation
       pass
   except NadzoringError as exc:
       print("A Nadzoring operation failed:", exc)
   except DNSError as exc:
       # Handle only DNS-related errors
       print("DNS operation failed:", exc)

Common exception types:

- ``DNSError`` — base for all DNS errors
  - ``DNSResolutionError`` — resolution failed
  - ``DNSTimeoutError`` — query timed out
  - ``DNSDomainNotFoundError`` — NXDOMAIN
  - ``DNSNoRecordsError`` — record type not present
- ``NetworkError`` — base for network errors
  - ``HostResolutionError`` — hostname resolution failed
  - ``ConnectionTimeoutError`` — connection timed out
  - ``UnsupportedPlatformError`` — OS not supported
- ``ARPError`` — base for ARP errors
  - ``ARPCacheRetrievalError`` — failed to read ARP cache
- ``ValidationError`` — input validation failed
  - ``InvalidIPAddressError`` — not a valid IP
  - ``InvalidDomainError`` — not a valid domain name
  - ``InvalidPortError`` — port out of range

----

Command-Line Error Handling
---------------------------

When using the CLI, errors are displayed in red and the command exits with a
non-zero status code. Use ``--quiet`` to suppress all output except the error
message.

.. code-block:: bash

   $ nadzoring dns resolve non-existent-domain.example
   DNS error: Domain does not exist
   $ echo $?
   1

   $ nadzoring dns resolve -o json non-existent-domain.example
   {"error": "Domain does not exist", ...}
   $ echo $?
   1

Timeout errors in CLI:

   When a lifetime timeout is exceeded, the command exits with an error
   message and a non-zero status code. Phase-specific timeouts (connect/read)
   are handled within the operation and returned as error fields where
   applicable.

.. code-block:: bash

   $ nadzoring dns resolve --timeout 1 slow-domain.example
   DNS error: Operation exceeded lifetime timeout
   $ echo $?
   1

----

Best Practices for Scripts
--------------------------

1. **Always check the error field** for DNS/network operations.
2. **Use truthiness checks** for functions that return empty dicts/lists.
3. **Use ``is_success()`` helper** for cleaner error checking.
4. **Use ``unwrap_or()``** for graceful degradation with defaults.
5. **Catch specific exceptions** only for system-level failures.
6. **Use timeout contexts** for operations that may hang.
7. **Use the Literal error types** for type-safe pattern matching.

Example robust monitoring script with timeout support:

.. code-block:: python

   from nadzoring.dns_lookup.utils import resolve_with_timer
   from nadzoring.dns_lookup.health import health_check_dns
   from nadzoring.dns_lookup.errors import DNSResolveError
   from nadzoring.utils.errors import NadzoringError
   from nadzoring.utils.result import is_success, unwrap_or
   from nadzoring.utils.timeout import TimeoutConfig

   def check_domain(domain: str, timeout_sec: float = 30.0) -> dict:
       """Safe domain checker — never raises."""
       timeout_config = TimeoutConfig(lifetime=timeout_sec)

       result = {
           "domain": domain,
           "a_record": None,
           "health_score": None,
           "error": None,
       }

       # DNS resolution with timeout
       a_result = resolve_with_timer(
           domain, "A",
           timeout_config=timeout_config,
       )

       if not is_success(a_result):
           # Type-safe error handling
           error: DNSResolveError | None = a_result.get("error")
           result["error"] = f"A record failed: {error}"
           return result

       result["a_record"] = a_result["records"][0]

       # Health check with fallback
       try:
           health = health_check_dns(domain, timeout_config=timeout_config)
           result["health_score"] = health["score"]
       except NadzoringError as exc:
           # System-level failure (unlikely, but possible)
           result["error"] = f"Health check system error: {exc}"

       return result

   # Use it
   data = check_domain("example.com", timeout_sec=10.0)
   if data["error"]:
       print(f"Check failed: {data['error']}")
   else:
       print(f"OK: {data['a_record']}  score={data['health_score']}")

   # Using unwrap_or for graceful degradation
   from nadzoring.utils.result import unwrap_or

   result = resolve_with_timer("example.com", "A")
   records = unwrap_or(result, ["0.0.0.0"])  # Fallback on error
   print(f"Resolved to: {records[0]}")

----

Error Literal Reference
-----------------------

**DNS Module** (``nadzoring.dns_lookup.errors``):

- ``DNSResolveError``: ``"Domain does not exist"``, ``"No records of requested type"``,
  ``"Query timeout"``, ``"Operation exceeded lifetime timeout"``, ``"Resolver error"``
- ``DNSReverseError``: ``"No PTR record"``, ``"No reverse DNS"``, ``"Query timeout"``,
  ``"Invalid IP address"``, ``"Resolver error"``
- ``DNSTraceError``: ``"Loop detected"``, ``"Delegation error"``, ``"No further delegation"``,
  ``"Timeout"``, ``"Domain does not exist"``, ``"No answer"``

**Security Module** (``nadzoring.security.errors``):

- ``SSLCertError``: ``"Certificate expired"``, ``"Certificate not yet valid"``,
  ``"Hostname mismatch"``, ``"Self-signed certificate"``, ``"Connection timeout"``,
  ``"SSL handshake failed"``, ``"Certificate verification failed"``, ``"No certificate returned"``
- ``HTTPHeaderError``: ``"Request timeout"``, ``"Connection refused"``,
  ``"SSL verification failed"``, ``"Too many redirects"``, ``"Invalid URL"``
- ``EmailSecurityError``: ``"No SPF record"``, ``"No DKIM record"``, ``"No DMARC record"``,
  ``"SPF lookup timeout"``, ``"DKIM lookup timeout"``, ``"DMARC lookup timeout"``

**Network Base Module** (``nadzoring.network_base.errors``):

- ``PingError``: ``"Host unreachable"``, ``"Timeout"``, ``"Permission denied (needs root)"``,
  ``"Invalid address"``
- ``TracerouteError``: ``"Permission denied (needs root)"``, ``"Command not found"``,
  ``"Network unreachable"``, ``"DNS resolution failed"``, ``"Timeout"``
- ``WHOISError``: ``"Command not found"``, ``"Query timeout"``, ``"No information found"``,
  ``"Invalid target"``
- ``PortScanError``: ``"Connection refused"``, ``"Timeout"``, ``"Host unreachable"``,
  ``"Invalid port range"``, ``"Resolution failed"``
- ``GeolocationError``: ``"API request failed"``, ``"Rate limit exceeded"``,
  ``"Invalid IP address"``, ``"Private IP address"``

**ARP Module** (``nadzoring.arp.errors``):

- ``ARPCacheError``: ``"Command not found"``, ``"Permission denied (needs root)"``,
  ``"Unsupported platform"``, ``"Failed to parse ARP cache output"``
- ``ARPSpoofingError``: ``"No network interface specified"``, ``"Packet capture failed"``,
  ``"No ARP packets captured"``


## Source: docs/source/installation.rst

Installation
============

Requirements
------------

- **Python 3.12** or higher
- **pip** (bundled with Python 3.12+)
- Supported operating systems: **Linux**, **Windows**, **macOS**

Optional system utilities (needed for specific commands):

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Utility
     - Required by
   * - ``traceroute`` / ``tracepath``
     - ``network-base traceroute`` (Linux)
   * - ``tracert``
     - ``network-base traceroute`` (Windows — built-in)
   * - ``whois``
     - ``network-base whois``
   * - ``ip`` / ``ifconfig`` / ``route``
     - ``network-base params``, ``network-base route`` (Linux)
   * - ``ss``
     - ``network-base connections`` (Linux)
   * - ``net-tools`` (``route -n``)
     - ``network-base params`` on some Linux distros
   * - ``dig``
     - ``security check-email`` (DNS TXT lookups — used when ``dnspython``
       is not installed)
   * - ``nslookup``
     - ``security check-email`` (second fallback after ``dig``)

Optional Python packages:

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Package
     - Required by
   * - ``dnspython``
     - ``security check-email`` (preferred; handles multi-chunk TXT records
       reliably).  Install with ``pip install dnspython``.

----

Stable Release (Recommended)
------------------------------

Install the latest stable version from PyPI:

.. code-block:: bash

   pip install nadzoring

Verify the installation:

.. code-block:: bash

   nadzoring --help

----

Development Version
-------------------

To install the latest development snapshot directly from GitHub:

.. code-block:: bash

   pip install git+https://github.com/alexeev-prog/nadzoring.git

Or clone and install in editable mode for contributing:

.. code-block:: bash

   git clone https://github.com/alexeev-prog/nadzoring.git
   cd nadzoring
   pip install -e ".[dev]"

----

Installing Optional System Dependencies
-----------------------------------------

**Linux (Debian / Ubuntu):**

.. code-block:: bash

   sudo apt update
   sudo apt install net-tools traceroute whois iproute2 dnsutils

**Linux (RHEL / CentOS / Fedora):**

.. code-block:: bash

   sudo dnf install net-tools traceroute whois iproute bind-utils

**macOS (Homebrew):**

.. code-block:: bash

   brew install iproute2mac whois

**Windows:**

``tracert`` and ``arp`` are built into Windows. No additional installs required
for basic functionality.

----

Installing Optional Python Dependencies
-----------------------------------------

For reliable email security checks (``security check-email``), install
``dnspython``:

.. code-block:: bash

   pip install dnspython

Without ``dnspython``, Nadzoring falls back to ``dig`` and then ``nslookup``
for DNS TXT record queries.  Multi-chunk TXT records (long SPF strings split
across multiple quoted segments) are handled correctly in all three cases, but
``dnspython`` is the most reliable option.

----

ARP Monitoring: Additional Setup
----------------------------------

The ``arp monitor-spoofing`` command uses `Scapy <https://scapy.net/>`_ for
raw packet capture, which requires elevated privileges on most systems.

**Linux** — grant raw-socket capability to avoid running as root:

.. code-block:: bash

   sudo setcap cap_net_raw+ep $(which python3)

Or simply run the command with ``sudo``.

**Windows** — run your terminal as Administrator.

**macOS** — run with ``sudo``.

----

Traceroute: Privilege Setup (Linux)
-------------------------------------

The ``network-base traceroute`` command requires raw-socket access on Linux.
Use one of the following approaches:

.. code-block:: bash

   # Option 1: run with sudo
   nadzoring network-base traceroute --sudo example.com

   # Option 2: grant capability to traceroute binary
   sudo setcap cap_net_raw+ep $(which traceroute)

   # Option 3: use tracepath (no root required — automatic fallback)
   # Nadzoring tries tracepath automatically if traceroute fails

----

Shell Completions
-----------------

Nadzoring provides tab-completion support for **bash**, **zsh**, **fish**, and
**PowerShell**. Enable it for your preferred shell using the commands below.

Bash
~~~~

Add to ``~/.bashrc`` (or ``~/.bash_profile`` on macOS):

.. code-block:: bash

   echo 'eval "$(nadzoring completion bash)"' >> ~/.bashrc
   source ~/.bashrc

Alternative — save to a file and source it:

.. code-block:: bash

   nadzoring completion bash > ~/.nadzoring-complete.bash
   echo 'source ~/.nadzoring-complete.bash' >> ~/.bashrc

Zsh
~~~

Add to ``~/.zshrc``:

.. code-block:: bash

   echo 'eval "$(nadzoring completion zsh)"' >> ~/.zshrc
   source ~/.zshrc

Or save to a file in your ``fpath``:

.. code-block:: bash

   nadzoring completion zsh > "${fpath[1]}/_nadzoring"

Fish
~~~~

Save directly to Fish completions directory:

.. code-block:: bash

   nadzoring completion fish > ~/.config/fish/completions/nadzoring.fish

Or source it temporarily:

.. code-block:: bash

   nadzoring completion fish | source

PowerShell
~~~~~~~~~~

Add to your PowerShell profile (``$PROFILE``):

.. code-block:: powershell

   nadzoring completion powershell >> $PROFILE

To reload the profile immediately:

.. code-block:: powershell

   . $PROFILE

Or use it in the current session only:

.. code-block:: powershell

   nadzoring completion powershell | Invoke-Expression

Testing Completions
~~~~~~~~~~~~~~~~~~~

After installation, type ``nadzoring `` followed by **TAB** to see available
commands:

.. code-block:: bash

   nadzoring [TAB]
   # Should show: arp  completion  dns  network-base  security

Type a command followed by space and **TAB** to see options:

.. code-block:: bash

   nadzoring dns [TAB]
   # Should show: resolve  reverse  check  trace  compare  health  benchmark  poisoning  monitor

Manual Activation (without saving to profile)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you don't want to modify your shell profile, you can activate completions
manually:

.. code-block:: bash

   # Bash / Zsh
   source <(nadzoring completion bash)

   # Fish
   nadzoring completion fish | source

   # PowerShell
   nadzoring completion powershell | Invoke-Expression

Troubleshooting Completions
~~~~~~~~~~~~~~~~~~~~~~~~~~~

**Completions not working?** Check these common issues:

1. **Shell not reloaded** — restart your terminal or run
   ``source ~/.bashrc`` (bash) / ``source ~/.zshrc`` (zsh)

2. **Wrong shell** — ensure you're using the correct completion command for
   your shell

3. **PATH issue** — verify ``nadzoring`` is in your PATH: ``which nadzoring``

4. **Completion not registered** — run the activation command directly to see
   if there are any errors

**Debugging bash completions:**

.. code-block:: bash

   # Enable debug output
   set -x
   nadzoring [TAB]
   set +x

**Check if completion is registered:**

.. code-block:: bash

   # Bash
   complete -p | grep nadzoring
   # Should output: complete -o nosort -F _nadzoring_completion nadzoring

   # Zsh
   echo $fpath | grep nadzoring

**Show installation hints:**

.. code-block:: bash

   nadzoring completion hints bash      # For bash
   nadzoring completion hints zsh       # For zsh
   nadzoring completion hints fish      # For fish
   nadzoring completion hints powershell  # For PowerShell

Completions Commands Reference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Command
     - Description
   * - ``nadzoring completion bash``
     - Generate bash completion script
   * - ``nadzoring completion zsh``
     - Generate zsh completion script
   * - ``nadzoring completion fish``
     - Generate fish completion script
   * - ``nadzoring completion powershell``
     - Generate PowerShell completion script
   * - ``nadzoring completion hints <shell>``
     - Show detailed installation hints

----

Verifying the Installation
--------------------------

Run a quick smoke test after installing:

.. code-block:: bash

   # Check tool is reachable
   nadzoring --help

   # Resolve a well-known domain
   nadzoring dns resolve google.com

   # Reverse DNS lookup
   nadzoring dns reverse 8.8.8.8

   # Ping a host
   nadzoring network-base ping 1.1.1.1

   # Show local network parameters
   nadzoring network-base params

   # Check an SSL certificate
   nadzoring security check-ssl example.com

   # Audit HTTP security headers
   nadzoring security check-headers https://example.com

   # Validate email security records
   nadzoring security check-email example.com

   # Test timeout configuration (slow operation will abort)
   nadzoring dns resolve --timeout 2 google.com

   # Test shell completions (if enabled)
   nadzoring [TAB]


## Source: docs/source/monitoring_dns.rst

Continuous DNS Monitoring
=========================

Nadzoring provides a built-in monitoring loop that periodically checks one
or more DNS servers, tracks trends over time, fires threshold-based alerts,
and persists all results to a JSONL log for later analysis.

----

Quick Start
-----------

Monitor ``example.com`` against two DNS servers every 60 seconds:

.. code-block:: bash

   nadzoring dns monitor example.com \
       -n 8.8.8.8 -n 1.1.1.1 \
       --interval 60 \
       --log-file dns_monitor.jsonl

Press **Ctrl-C** to stop. A statistical summary prints automatically.

Analyse the log afterwards:

.. code-block:: bash

   nadzoring dns monitor-report dns_monitor.jsonl
   nadzoring dns monitor-report dns_monitor.jsonl --server 8.8.8.8 -o json

----

CLI Reference: ``dns monitor``
--------------------------------

.. code-block:: text

   nadzoring dns monitor [OPTIONS] DOMAIN

.. list-table::
   :header-rows: 1
   :widths: 24 6 52 18

   * - Option
     - Short
     - Description
     - Default
   * - ``--nameservers``
     - ``-n``
     - DNS server IP to monitor (repeatable)
     - ``8.8.8.8``, ``1.1.1.1``
   * - ``--interval``
     - ``-i``
     - Seconds between monitoring cycles
     - ``60``
   * - ``--type``
     - ``-t``
     - Record type: A, AAAA, MX, NS, TXT
     - ``A``
   * - ``--queries``
     - ``-q``
     - Queries per server per cycle
     - ``3``
   * - ``--max-rt``
     -
     - Alert threshold: max avg response time (ms)
     - ``500``
   * - ``--min-success``
     -
     - Alert threshold: minimum success rate (0–1)
     - ``0.95``
   * - ``--no-health``
     -
     - Skip health check each cycle
     - ``False``
   * - ``--log-file``
     - ``-l``
     - JSONL file to append all cycle results to
     - None
   * - ``--cycles``
     - ``-c``
     - Stop after N cycles (0 = indefinite)
     - ``0``
   * - ``--output``
     - ``-o``
     - Output format: table, json, csv, html
     - ``table``
   * - ``--quiet``
     -
     - Suppress all console output
     - ``False``
   * - ``--timeout``
     -
     - Lifetime timeout (seconds)
     - ``30.0``
   * - ``--connect-timeout``
     -
     - Connection timeout (seconds). Falls back to ``--timeout``.
     - ``5.0``
   * - ``--read-timeout``
     -
     - Read timeout (seconds). Falls back to ``--timeout``.
     - ``10.0``

**Examples:**

.. code-block:: bash

   # Monitor with default servers, save log
   nadzoring dns monitor example.com \
       --interval 60 \
       --log-file dns_monitor.jsonl

   # Strict thresholds — alert above 150 ms or below 99 % success
   nadzoring dns monitor example.com \
       -n 8.8.8.8 -n 1.1.1.1 -n 9.9.9.9 \
       --interval 30 \
       --max-rt 150 --min-success 0.99 \
       --log-file dns_monitor.jsonl

   # Run exactly 10 cycles and save a JSON report (great for CI)
   nadzoring dns monitor example.com --cycles 10 -o json --save report.json

   # Quiet mode for cron / systemd
   nadzoring dns monitor example.com \
       --quiet --log-file /var/log/nadzoring/dns_monitor.jsonl

   # Custom timeouts for slow networks
   nadzoring dns monitor example.com \
       --connect-timeout 10 --read-timeout 20 --interval 60

----

CLI Reference: ``dns monitor-report``
---------------------------------------

Analyse a saved JSONL log and print aggregated per-server statistics:

.. code-block:: text

   nadzoring dns monitor-report [OPTIONS] LOG_FILE

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Option
     - Description
   * - ``--server / -s``
     - Filter statistics to a specific server IP

.. code-block:: bash

   # Basic analysis
   nadzoring dns monitor-report dns_monitor.jsonl

   # Filter to a single server, export JSON
   nadzoring dns monitor-report dns_monitor.jsonl --server 8.8.8.8 -o json

   # Save as HTML report for dashboard
   nadzoring dns monitor-report dns_monitor.jsonl -o html --save report.html

----

What Happens Each Cycle
------------------------

1. **Benchmark** — sends ``--queries`` queries to each server and records
   average, min, and max response times plus the success rate.

2. **Resolve** — one additional query captures the current DNS records
   returned by each server.

3. **Health check** (skip with ``--no-health``) — computes an overall
   score (0–100) across A, AAAA, MX, NS, TXT, and CNAME records.

4. **Threshold evaluation** — compares metrics against configured
   thresholds and generates alert events for any breaches.

5. **Alert dispatch** — calls the configured ``alert_callback`` (if any)
   and prints warnings to the console.

6. **Persistence** — appends a JSON line to the log file (if configured).

7. **Sleep** — waits ``--interval`` seconds before the next cycle.

----

Alert Types
-----------

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Type
     - Triggered when
   * - ``resolution_failure``
     - All queries failed (success rate = 0 %)
   * - ``high_latency``
     - Average response time exceeds ``--max-rt``
   * - ``low_success_rate``
     - Success rate falls below ``--min-success``
   * - ``health_degraded``
     - DNS health score drops below 80

----

Log File Format
---------------

Each line in the JSONL log is a complete cycle result:

.. code-block:: json

   {
     "cycle": 42,
     "timestamp": "2025-06-01T14:23:10.123456+00:00",
     "domain": "example.com",
     "samples": [
       {
         "server": "8.8.8.8",
         "timestamp": "2025-06-01T14:23:10.123456+00:00",
         "avg_response_time_ms": 18.4,
         "min_response_time_ms": 14.1,
         "max_response_time_ms": 24.7,
         "success_rate": 1.0,
         "records": ["93.184.216.34"],
         "error": null
       }
     ],
     "health_score": 85,
     "health_status": "healthy",
     "alerts": []
   }

----

Python API
----------

Basic continuous monitoring
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

   from nadzoring.dns_lookup.monitor import DNSMonitor, MonitorConfig
   from nadzoring.utils.timeout import TimeoutConfig

   timeout_config = TimeoutConfig(connect=3.0, read=10.0, lifetime=30.0)

   config = MonitorConfig(
       domain="example.com",
       nameservers=["8.8.8.8", "1.1.1.1"],
       interval=60.0,
       max_response_time_ms=500.0,
       min_success_rate=0.95,
       log_file="dns_monitor.jsonl",
       timeout_config=timeout_config,
   )

   monitor = DNSMonitor(config)
   monitor.run()
   print(monitor.report())

Custom alert callback
~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

   import requests
   from nadzoring.dns_lookup.monitor import AlertEvent, DNSMonitor, MonitorConfig
   from nadzoring.utils.timeout import TimeoutConfig

   SLACK_WEBHOOK = "https://hooks.slack.com/services/T.../B.../..."

   timeout_config = TimeoutConfig(connect=2.0, read=8.0)


   def send_slack_alert(alert: AlertEvent) -> None:
       requests.post(
           SLACK_WEBHOOK,
           json={"text": f":warning: *{alert.alert_type}* — {alert.message}"},
           timeout=5,
       )


   config = MonitorConfig(
       domain="example.com",
       nameservers=["8.8.8.8"],
       interval=30.0,
       max_response_time_ms=200.0,
       alert_callback=send_slack_alert,
       timeout_config=timeout_config,
   )
   DNSMonitor(config).run()

Finite-cycle monitoring (CI / cron)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

   from nadzoring.dns_lookup.monitor import DNSMonitor, MonitorConfig
   from nadzoring.utils.timeout import TimeoutConfig
   from statistics import mean

   timeout_config = TimeoutConfig(connect=2.0, read=8.0)

   config = MonitorConfig(
       domain="example.com",
       nameservers=["8.8.8.8", "1.1.1.1"],
       interval=10.0,
       queries_per_sample=5,
       run_health_check=False,
       timeout_config=timeout_config,
   )
   monitor = DNSMonitor(config)
   history = monitor.run_cycles(6)

   rts = [
       s.avg_response_time_ms
       for c in history
       for s in c.samples
       if s.avg_response_time_ms is not None
   ]
   print(f"Mean RT over {len(history)} cycles: {mean(rts):.1f}ms")
   print(monitor.report())

Analysing a historical log
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

   from nadzoring.dns_lookup.monitor import load_log
   from statistics import mean

   cycles = load_log("dns_monitor.jsonl")

   rts = [
       s["avg_response_time_ms"]
       for c in cycles
       for s in c["samples"]
       if s["server"] == "8.8.8.8" and s["avg_response_time_ms"] is not None
   ]
   alerts = [a for c in cycles for a in c.get("alerts", [])]

   print(f"Cycles      : {len(cycles)}")
   print(f"Avg RT (ms) : {mean(rts):.2f}")
   print(f"Alerts      : {len(alerts)}")

----

Scheduling
----------

Cron (one cycle per minute)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: cron

   * * * * * root nadzoring dns monitor example.com \
       --cycles 1 --quiet \
       --log-file /var/log/nadzoring/dns_monitor.jsonl

.. note::

   Use ``--cycles 1`` with cron — the process exits after one check
   and cron handles the interval.

systemd service (recommended for production)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Create ``/etc/systemd/system/nadzoring-dns-monitor.service``:

.. code-block:: ini

   [Unit]
   Description=Nadzoring DNS Monitor
   After=network-online.target
   Wants=network-online.target

   [Service]
   Type=simple
   User=nobody
   ExecStart=/usr/local/bin/nadzoring dns monitor example.com \
       -n 8.8.8.8 -n 1.1.1.1 \
       --interval 60 \
       --max-rt 300 \
       --min-success 0.95 \
       --log-file /var/log/nadzoring/dns_monitor.jsonl \
       --quiet
   Restart=on-failure
   RestartSec=10
   StandardOutput=journal
   StandardError=journal

   [Install]
   WantedBy=multi-user.target

.. code-block:: bash

   sudo systemctl daemon-reload
   sudo systemctl enable --now nadzoring-dns-monitor
   sudo journalctl -u nadzoring-dns-monitor -f

----

Complete Automation Script
---------------------------

.. code-block:: bash

   #!/usr/bin/env bash
   # dns_health_check.sh — hourly DNS health snapshot for cron
   set -euo pipefail

   DOMAIN="${1:-example.com}"
   LOG_DIR="/var/log/nadzoring"
   TODAY=$(date -u +%Y%m%d)
   TS=$(date -u +%Y%m%d_%H%M%S)
   DAILY_LOG="${LOG_DIR}/dns_monitor_${TODAY}.jsonl"
   REPORT_DIR="/var/www/html/dns-reports"

   mkdir -p "$LOG_DIR" "$REPORT_DIR"

   nadzoring dns monitor "$DOMAIN" \
       -n 8.8.8.8 -n 1.1.1.1 \
       --cycles 1 --max-rt 300 --min-success 0.95 \
       --log-file "$DAILY_LOG" --quiet

   nadzoring dns health "$DOMAIN" \
       -o json --save "${LOG_DIR}/health_${TS}.json" --quiet

   nadzoring dns benchmark --domain "$DOMAIN" --queries 5 \
       -o json --save "${LOG_DIR}/benchmark_${TS}.json" --quiet

   nadzoring dns monitor-report "$DAILY_LOG" \
       -o html --save "${REPORT_DIR}/report_${TODAY}.html"

   find "$LOG_DIR" -name "dns_monitor_*.jsonl" -mtime +30 -delete
   find "$LOG_DIR" -name "health_*.json"       -mtime +7  -delete
   find "$LOG_DIR" -name "benchmark_*.json"    -mtime +7  -delete


