networkmgmt 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- networkmgmt/__init__.py +65 -0
- networkmgmt/__main__.py +93 -0
- networkmgmt/discovery/__init__.py +38 -0
- networkmgmt/discovery/_util.py +45 -0
- networkmgmt/discovery/categorize.py +154 -0
- networkmgmt/discovery/cli.py +235 -0
- networkmgmt/discovery/lldp.py +240 -0
- networkmgmt/discovery/mermaid.py +980 -0
- networkmgmt/discovery/models.py +85 -0
- networkmgmt/discovery/oui.py +99 -0
- networkmgmt/discovery/scanner.py +826 -0
- networkmgmt/discovery/snmp.py +372 -0
- networkmgmt/snmp_vlan_dump/__init__.py +16 -0
- networkmgmt/snmp_vlan_dump/_util.py +124 -0
- networkmgmt/snmp_vlan_dump/cli.py +92 -0
- networkmgmt/snmp_vlan_dump/collector.py +191 -0
- networkmgmt/snmp_vlan_dump/formatters.py +162 -0
- networkmgmt/snmp_vlan_dump/mermaid.py +331 -0
- networkmgmt/snmp_vlan_dump/models.py +43 -0
- networkmgmt/snmp_vlan_dump/snmp.py +103 -0
- networkmgmt/switchctrl/__init__.py +30 -0
- networkmgmt/switchctrl/base/__init__.py +19 -0
- networkmgmt/switchctrl/base/client.py +61 -0
- networkmgmt/switchctrl/base/managers.py +94 -0
- networkmgmt/switchctrl/base/transport.py +38 -0
- networkmgmt/switchctrl/cli.py +269 -0
- networkmgmt/switchctrl/exceptions.py +33 -0
- networkmgmt/switchctrl/factory.py +54 -0
- networkmgmt/switchctrl/models/__init__.py +20 -0
- networkmgmt/switchctrl/models/port.py +56 -0
- networkmgmt/switchctrl/models/stats.py +20 -0
- networkmgmt/switchctrl/models/system.py +38 -0
- networkmgmt/switchctrl/models/vlan.py +24 -0
- networkmgmt/switchctrl/vendors/__init__.py +9 -0
- networkmgmt/switchctrl/vendors/cisco/__init__.py +5 -0
- networkmgmt/switchctrl/vendors/cisco/client.py +130 -0
- networkmgmt/switchctrl/vendors/cisco/managers.py +421 -0
- networkmgmt/switchctrl/vendors/common/__init__.py +15 -0
- networkmgmt/switchctrl/vendors/common/cisco_cli.py +194 -0
- networkmgmt/switchctrl/vendors/common/cisco_managers.py +392 -0
- networkmgmt/switchctrl/vendors/mikrotik/__init__.py +5 -0
- networkmgmt/switchctrl/vendors/mikrotik/client.py +129 -0
- networkmgmt/switchctrl/vendors/mikrotik/managers.py +373 -0
- networkmgmt/switchctrl/vendors/mikrotik/rest.py +129 -0
- networkmgmt/switchctrl/vendors/mikrotik/ssh.py +136 -0
- networkmgmt/switchctrl/vendors/netgear/__init__.py +5 -0
- networkmgmt/switchctrl/vendors/netgear/client.py +47 -0
- networkmgmt/switchctrl/vendors/qnap/__init__.py +5 -0
- networkmgmt/switchctrl/vendors/qnap/client.py +168 -0
- networkmgmt/switchctrl/vendors/qnap/rest.py +240 -0
- networkmgmt/switchctrl/vendors/qnap/utils.py +21 -0
- networkmgmt-0.0.1.dist-info/METADATA +367 -0
- networkmgmt-0.0.1.dist-info/RECORD +56 -0
- networkmgmt-0.0.1.dist-info/WHEEL +4 -0
- networkmgmt-0.0.1.dist-info/entry_points.txt +5 -0
- networkmgmt-0.0.1.dist-info/licenses/LICENSE.md +163 -0
networkmgmt/__init__.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Multi-Vendor Switch Management Library.
|
|
2
|
+
|
|
3
|
+
Provides programmatic management of network switches from multiple vendors
|
|
4
|
+
(QNAP, MikroTik, Netgear) using a unified API.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.0.1"
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any, Callable, Dict
|
|
12
|
+
|
|
13
|
+
from loguru import logger as glogger
|
|
14
|
+
|
|
15
|
+
glogger.disable(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _loguru_skiplog_filter(record: dict) -> bool: # type: ignore[type-arg]
|
|
19
|
+
"""Filter function to hide records with ``extra['skiplog']`` set."""
|
|
20
|
+
return not record.get("extra", {}).get("skiplog", False)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def configure_logging(
|
|
24
|
+
loguru_filter: Callable[[Dict[str, Any]], bool] = _loguru_skiplog_filter,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Configure a default ``loguru`` sink with a convenient format and filter."""
|
|
27
|
+
os.environ["LOGURU_LEVEL"] = os.getenv("LOGURU_LEVEL", "DEBUG")
|
|
28
|
+
glogger.remove()
|
|
29
|
+
logger_fmt: str = (
|
|
30
|
+
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{module}</cyan>::<cyan>{extra[classname]}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
|
|
31
|
+
)
|
|
32
|
+
glogger.add(sys.stderr, level=os.getenv("LOGURU_LEVEL"), format=logger_fmt, filter=loguru_filter) # type: ignore[arg-type]
|
|
33
|
+
glogger.configure(extra={"classname": "None", "skiplog": False})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# Import vendors to trigger registration
|
|
37
|
+
import networkmgmt.switchctrl.vendors # noqa: F401, E402
|
|
38
|
+
from networkmgmt.switchctrl.base.client import BaseSwitchClient
|
|
39
|
+
from networkmgmt.switchctrl.base.transport import BaseTransport
|
|
40
|
+
from networkmgmt.switchctrl.exceptions import (
|
|
41
|
+
APIError,
|
|
42
|
+
AuthenticationError,
|
|
43
|
+
LACPError,
|
|
44
|
+
PortError,
|
|
45
|
+
SSHError,
|
|
46
|
+
SwitchError,
|
|
47
|
+
VLANError,
|
|
48
|
+
)
|
|
49
|
+
from networkmgmt.switchctrl.factory import create_switch, list_vendors
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"glogger",
|
|
53
|
+
"configure_logging",
|
|
54
|
+
"create_switch",
|
|
55
|
+
"list_vendors",
|
|
56
|
+
"BaseSwitchClient",
|
|
57
|
+
"BaseTransport",
|
|
58
|
+
"SwitchError",
|
|
59
|
+
"AuthenticationError",
|
|
60
|
+
"APIError",
|
|
61
|
+
"SSHError",
|
|
62
|
+
"VLANError",
|
|
63
|
+
"PortError",
|
|
64
|
+
"LACPError",
|
|
65
|
+
]
|
networkmgmt/__main__.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Orchestrator CLI — dispatches to sub-CLIs.
|
|
2
|
+
|
|
3
|
+
Sub-commands:
|
|
4
|
+
switchctrl Multi-vendor switch management (monitor, VLAN, port config)
|
|
5
|
+
discover Network topology discovery (ARP, DNS, SNMP, LLDP, traceroute)
|
|
6
|
+
vlan-dump SNMP VLAN-port dump for Netgear switches
|
|
7
|
+
|
|
8
|
+
Examples:
|
|
9
|
+
networkmgmt switchctrl --vendor cisco --host 192.168.1.254 \\
|
|
10
|
+
--username admin --password <PW> --enable-password <EN> monitor
|
|
11
|
+
|
|
12
|
+
networkmgmt discover -i eth0 --nmap -o topology.md
|
|
13
|
+
|
|
14
|
+
networkmgmt vlan-dump 192.168.101.38 public --markdown
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
from tabulate import tabulate
|
|
23
|
+
|
|
24
|
+
from networkmgmt import __version__, configure_logging
|
|
25
|
+
from networkmgmt import glogger
|
|
26
|
+
|
|
27
|
+
COMMANDS = {
|
|
28
|
+
"switchctrl": ("networkmgmt.switchctrl.cli", "Multi-vendor switch management"),
|
|
29
|
+
"discover": ("networkmgmt.discovery.cli", "Network topology discovery"),
|
|
30
|
+
"vlan-dump": ("networkmgmt.snmp_vlan_dump.cli", "SNMP VLAN-port dump"),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _print_usage() -> None:
|
|
35
|
+
print("usage: networkmgmt <command> [options]\n")
|
|
36
|
+
print("Available commands:")
|
|
37
|
+
for cmd, (_, desc) in COMMANDS.items():
|
|
38
|
+
print(f" {cmd:14s} {desc}")
|
|
39
|
+
print("\nRun 'networkmgmt <command> --help' for command-specific options.")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _print_startup_banner() -> None:
|
|
43
|
+
startup_rows = [
|
|
44
|
+
["version", __version__],
|
|
45
|
+
["github", "https://github.com/vroomfondel/networkmgmt"],
|
|
46
|
+
["pypi", "https://pypi.org/project/networkmgmt"],
|
|
47
|
+
["Docker Hub", "https://hub.docker.com/r/xomoxcc/networkmgmt"],
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
for var in ("GITHUB_REF", "GITHUB_SHA", "BUILDTIME"):
|
|
51
|
+
val = os.environ.get(var)
|
|
52
|
+
if val and not val.endswith("_is_undefined"):
|
|
53
|
+
startup_rows.append([var, val])
|
|
54
|
+
|
|
55
|
+
table_str = tabulate(startup_rows, tablefmt="mixed_grid")
|
|
56
|
+
lines = table_str.split("\n")
|
|
57
|
+
table_width = len(lines[0])
|
|
58
|
+
title = "networkmgmt starting up"
|
|
59
|
+
title_border = "┍" + "━" * (table_width - 2) + "┑"
|
|
60
|
+
title_row = "│ " + title.center(table_width - 4) + " │"
|
|
61
|
+
separator = lines[0].replace("┍", "┝").replace("┑", "┥").replace("┯", "┿")
|
|
62
|
+
|
|
63
|
+
glogger.opt(raw=True).info(
|
|
64
|
+
"\n{}\n", title_border + "\n" + title_row + "\n" + separator + "\n" + "\n".join(lines[1:])
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def main() -> None:
|
|
69
|
+
"""Main entry point — dispatch to sub-CLI."""
|
|
70
|
+
configure_logging()
|
|
71
|
+
_print_startup_banner()
|
|
72
|
+
|
|
73
|
+
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
|
|
74
|
+
_print_usage()
|
|
75
|
+
sys.exit(0 if len(sys.argv) >= 2 else 1)
|
|
76
|
+
|
|
77
|
+
command = sys.argv[1]
|
|
78
|
+
if command not in COMMANDS:
|
|
79
|
+
print(f"networkmgmt: unknown command '{command}'\n", file=sys.stderr)
|
|
80
|
+
_print_usage()
|
|
81
|
+
sys.exit(1)
|
|
82
|
+
|
|
83
|
+
module_path, _ = COMMANDS[command]
|
|
84
|
+
|
|
85
|
+
# Import and call the sub-CLI's main(), passing remaining args
|
|
86
|
+
from importlib import import_module
|
|
87
|
+
|
|
88
|
+
module = import_module(module_path)
|
|
89
|
+
module.main(sys.argv[2:])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
main()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Network topology discovery subpackage.
|
|
2
|
+
|
|
3
|
+
Provides tools for discovering network topology via ARP scanning, reverse DNS,
|
|
4
|
+
MAC vendor lookup, SNMP bridge tables, LLDP, nmap, and traceroute. Generates
|
|
5
|
+
Mermaid flowchart diagrams or JSON output.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from networkmgmt.discovery.lldp import LldpDiscovery
|
|
9
|
+
from networkmgmt.discovery.mermaid import MermaidGenerator
|
|
10
|
+
from networkmgmt.discovery.models import (
|
|
11
|
+
DeviceCategory,
|
|
12
|
+
DiscoveredHost,
|
|
13
|
+
L2TopologyEntry,
|
|
14
|
+
NetworkInterface,
|
|
15
|
+
NetworkTopology,
|
|
16
|
+
SubnetScan,
|
|
17
|
+
SwitchPortMapping,
|
|
18
|
+
TracerouteHop,
|
|
19
|
+
TraceroutePath,
|
|
20
|
+
)
|
|
21
|
+
from networkmgmt.discovery.scanner import NetworkTopologyScanner
|
|
22
|
+
from networkmgmt.discovery.snmp import SnmpBridgeDiscovery
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"NetworkTopologyScanner",
|
|
26
|
+
"MermaidGenerator",
|
|
27
|
+
"SnmpBridgeDiscovery",
|
|
28
|
+
"LldpDiscovery",
|
|
29
|
+
"DeviceCategory",
|
|
30
|
+
"DiscoveredHost",
|
|
31
|
+
"L2TopologyEntry",
|
|
32
|
+
"NetworkInterface",
|
|
33
|
+
"NetworkTopology",
|
|
34
|
+
"SubnetScan",
|
|
35
|
+
"SwitchPortMapping",
|
|
36
|
+
"TracerouteHop",
|
|
37
|
+
"TraceroutePath",
|
|
38
|
+
]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Shared helper functions for network topology discovery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
|
|
9
|
+
from loguru import logger
|
|
10
|
+
|
|
11
|
+
# Hostname suffixes to strip for shorter labels
|
|
12
|
+
_HOSTNAME_SUFFIXES = (".fritz.box", ".local", ".lan")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _strip_hostname_suffix(hostname: str) -> str:
|
|
16
|
+
"""Strip common DNS suffixes from hostnames for shorter labels."""
|
|
17
|
+
lower = hostname.lower()
|
|
18
|
+
for suffix in _HOSTNAME_SUFFIXES:
|
|
19
|
+
if lower.endswith(suffix):
|
|
20
|
+
return hostname[: -len(suffix)]
|
|
21
|
+
return hostname
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _run_cmd(cmd: list[str], timeout: int = 30) -> str:
|
|
25
|
+
"""Run a subprocess command and return stdout."""
|
|
26
|
+
try:
|
|
27
|
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
|
28
|
+
return result.stdout
|
|
29
|
+
except (subprocess.TimeoutExpired, FileNotFoundError) as e:
|
|
30
|
+
logger.debug(f"Command {cmd[0]} failed: {e}")
|
|
31
|
+
return ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _validate_interface_name(name: str) -> bool:
|
|
35
|
+
"""Validate interface name to prevent injection."""
|
|
36
|
+
return bool(re.match(r"^[a-zA-Z0-9._-]+$", name))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _validate_ip(ip: str) -> bool:
|
|
40
|
+
"""Validate IP address string."""
|
|
41
|
+
try:
|
|
42
|
+
ipaddress.ip_address(ip)
|
|
43
|
+
return True
|
|
44
|
+
except ValueError:
|
|
45
|
+
return False
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Device category classification rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from networkmgmt.discovery.models import DeviceCategory, DiscoveredHost
|
|
6
|
+
|
|
7
|
+
# Match patterns: (category, vendor_substrings, hostname_patterns)
|
|
8
|
+
_CATEGORY_RULES: list[tuple[DeviceCategory, list[str], list[str]]] = [
|
|
9
|
+
(
|
|
10
|
+
DeviceCategory.INFRASTRUCTURE,
|
|
11
|
+
[
|
|
12
|
+
"NETGEAR",
|
|
13
|
+
"Netgear",
|
|
14
|
+
"Ubiquiti",
|
|
15
|
+
"TP-LINK",
|
|
16
|
+
"TP-Link",
|
|
17
|
+
"Cisco",
|
|
18
|
+
],
|
|
19
|
+
[
|
|
20
|
+
"switch",
|
|
21
|
+
"gs108",
|
|
22
|
+
"gs305",
|
|
23
|
+
"efh24",
|
|
24
|
+
"gs116",
|
|
25
|
+
],
|
|
26
|
+
),
|
|
27
|
+
(
|
|
28
|
+
DeviceCategory.SERVER,
|
|
29
|
+
[
|
|
30
|
+
"Raspberry Pi",
|
|
31
|
+
"Super Micro",
|
|
32
|
+
"Supermicro",
|
|
33
|
+
"UGREEN",
|
|
34
|
+
"Ugreen",
|
|
35
|
+
],
|
|
36
|
+
[
|
|
37
|
+
"node",
|
|
38
|
+
"nas",
|
|
39
|
+
"supermicro",
|
|
40
|
+
"rpi",
|
|
41
|
+
"raspi",
|
|
42
|
+
"thinkcentre",
|
|
43
|
+
"acerrevo",
|
|
44
|
+
"revo",
|
|
45
|
+
"peekabooboo",
|
|
46
|
+
],
|
|
47
|
+
),
|
|
48
|
+
(
|
|
49
|
+
DeviceCategory.IOT,
|
|
50
|
+
[
|
|
51
|
+
"Espressif",
|
|
52
|
+
"BroadLink",
|
|
53
|
+
"Hangzhou BroadLink",
|
|
54
|
+
"Nuki",
|
|
55
|
+
"Climax",
|
|
56
|
+
"Ogemray",
|
|
57
|
+
"Shenzhen Ogemray",
|
|
58
|
+
],
|
|
59
|
+
[
|
|
60
|
+
"tasmota",
|
|
61
|
+
"nous",
|
|
62
|
+
"shelly",
|
|
63
|
+
"plug",
|
|
64
|
+
"sensor",
|
|
65
|
+
],
|
|
66
|
+
),
|
|
67
|
+
(
|
|
68
|
+
DeviceCategory.PHONE,
|
|
69
|
+
[
|
|
70
|
+
"Grandstream",
|
|
71
|
+
"snom",
|
|
72
|
+
],
|
|
73
|
+
[
|
|
74
|
+
"wp820",
|
|
75
|
+
"gxp",
|
|
76
|
+
"phone",
|
|
77
|
+
"sip",
|
|
78
|
+
],
|
|
79
|
+
),
|
|
80
|
+
(
|
|
81
|
+
DeviceCategory.MEDIA,
|
|
82
|
+
[
|
|
83
|
+
"Google, Inc.",
|
|
84
|
+
"Google",
|
|
85
|
+
"NVIDIA",
|
|
86
|
+
"Samsung",
|
|
87
|
+
"HUMAX",
|
|
88
|
+
"Slim Devices",
|
|
89
|
+
"Denon",
|
|
90
|
+
"D&M Holdings",
|
|
91
|
+
"StreamUnlimited",
|
|
92
|
+
],
|
|
93
|
+
[
|
|
94
|
+
"chromecast",
|
|
95
|
+
"shield",
|
|
96
|
+
"tv",
|
|
97
|
+
"denon",
|
|
98
|
+
"humax",
|
|
99
|
+
"squeezebox",
|
|
100
|
+
],
|
|
101
|
+
),
|
|
102
|
+
(
|
|
103
|
+
DeviceCategory.HOME_AUTOMATION,
|
|
104
|
+
[
|
|
105
|
+
"Philips Lighting",
|
|
106
|
+
"Nabu Casa",
|
|
107
|
+
"Weinzierl",
|
|
108
|
+
"Fa. GIRA",
|
|
109
|
+
"GIRA",
|
|
110
|
+
"iRobot",
|
|
111
|
+
],
|
|
112
|
+
[
|
|
113
|
+
"hue",
|
|
114
|
+
"homeassistant",
|
|
115
|
+
"home-assistant",
|
|
116
|
+
"knx",
|
|
117
|
+
"roomba",
|
|
118
|
+
],
|
|
119
|
+
),
|
|
120
|
+
(
|
|
121
|
+
DeviceCategory.COMPUTER,
|
|
122
|
+
[
|
|
123
|
+
"HP Inc.",
|
|
124
|
+
"Hewlett Packard",
|
|
125
|
+
"HP",
|
|
126
|
+
"Brother",
|
|
127
|
+
"Intel",
|
|
128
|
+
"Part II Research",
|
|
129
|
+
"Realtek",
|
|
130
|
+
"REALTEK",
|
|
131
|
+
],
|
|
132
|
+
[
|
|
133
|
+
"printer",
|
|
134
|
+
"brother",
|
|
135
|
+
"laptop",
|
|
136
|
+
],
|
|
137
|
+
),
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _categorize_host(host: DiscoveredHost) -> DeviceCategory:
|
|
142
|
+
"""Classify a host into a device category by vendor and hostname patterns."""
|
|
143
|
+
vendor_lower = host.vendor.lower()
|
|
144
|
+
hostname_lower = host.hostname.lower()
|
|
145
|
+
|
|
146
|
+
for category, vendor_patterns, hostname_patterns in _CATEGORY_RULES:
|
|
147
|
+
for vp in vendor_patterns:
|
|
148
|
+
if vp.lower() in vendor_lower:
|
|
149
|
+
return category
|
|
150
|
+
for hp in hostname_patterns:
|
|
151
|
+
if hp in hostname_lower:
|
|
152
|
+
return category
|
|
153
|
+
|
|
154
|
+
return DeviceCategory.OTHER
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""CLI entry point for network topology discovery — standalone-capable."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import ipaddress
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from loguru import logger
|
|
11
|
+
|
|
12
|
+
from networkmgmt.discovery.mermaid import MermaidGenerator
|
|
13
|
+
from networkmgmt.discovery.scanner import NetworkTopologyScanner
|
|
14
|
+
from networkmgmt.discovery.snmp import HAS_PYSNMP
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_args(args: list[str] | None = None) -> argparse.Namespace:
|
|
18
|
+
"""Build argparse parser for network topology discovery."""
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
description="Network topology discovery with Mermaid diagram output",
|
|
21
|
+
)
|
|
22
|
+
parser.add_argument(
|
|
23
|
+
"-i",
|
|
24
|
+
"--interface",
|
|
25
|
+
help="Network interface(s), comma-separated for multi-subnet (default: auto-detect)",
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"-t",
|
|
29
|
+
"--targets",
|
|
30
|
+
help="Traceroute targets: comma-separated IPs, CIDR (192.168.1.0/24), or range (192.168.1.1-254)",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"--nmap",
|
|
34
|
+
action="store_true",
|
|
35
|
+
help="Enable nmap service detection",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"--top-ports",
|
|
39
|
+
type=int,
|
|
40
|
+
default=100,
|
|
41
|
+
help="nmap top ports to scan (default: 100)",
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"-o",
|
|
45
|
+
"--output",
|
|
46
|
+
help="Output file (default: stdout)",
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument(
|
|
49
|
+
"--format",
|
|
50
|
+
choices=["mermaid", "json"],
|
|
51
|
+
default="mermaid",
|
|
52
|
+
help="Output format (default: mermaid)",
|
|
53
|
+
)
|
|
54
|
+
parser.add_argument(
|
|
55
|
+
"--timeout",
|
|
56
|
+
type=int,
|
|
57
|
+
default=10,
|
|
58
|
+
help="Scan timeout in seconds (default: 10)",
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument(
|
|
61
|
+
"--max-hops",
|
|
62
|
+
type=int,
|
|
63
|
+
default=30,
|
|
64
|
+
help="Max traceroute hops (default: 30)",
|
|
65
|
+
)
|
|
66
|
+
parser.add_argument(
|
|
67
|
+
"--trace-local",
|
|
68
|
+
action="store_true",
|
|
69
|
+
help="Run tracepath to all discovered LAN hosts to detect switch hierarchy",
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--switches",
|
|
73
|
+
help="SNMP L2 discovery: comma-separated switch IPs with optional community "
|
|
74
|
+
"(e.g. 192.168.101.38:public,192.168.101.19). Default community: public",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--lldp-collect",
|
|
78
|
+
metavar="DIR",
|
|
79
|
+
help="SSH into discovered hosts, run lldpctl -f json, write results to DIR/<ip>.json",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument(
|
|
82
|
+
"--lldp-dir",
|
|
83
|
+
metavar="DIR",
|
|
84
|
+
help="Read LLDP data from DIR/<ip>.json files for L2 topology (no SSH needed)",
|
|
85
|
+
)
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
"--topology",
|
|
88
|
+
help="Manual L2 topology: comma-separated HOST_IP:SWITCH_IP:PORT_NAME entries "
|
|
89
|
+
"(e.g. 192.168.101.50:192.168.101.19:g3,192.168.101.51:192.168.101.19:g4)",
|
|
90
|
+
)
|
|
91
|
+
parser.add_argument(
|
|
92
|
+
"-d",
|
|
93
|
+
"--diagram-style",
|
|
94
|
+
choices=MermaidGenerator.DIAGRAM_STYLES,
|
|
95
|
+
default="auto",
|
|
96
|
+
help="Diagram style: auto (default), flat, categorized, hierarchical",
|
|
97
|
+
)
|
|
98
|
+
parser.add_argument(
|
|
99
|
+
"--direction",
|
|
100
|
+
choices=["LR", "TD"],
|
|
101
|
+
default="",
|
|
102
|
+
help="Mermaid flowchart direction (default: auto — TD for 40+ hosts, LR otherwise)",
|
|
103
|
+
)
|
|
104
|
+
parser.add_argument(
|
|
105
|
+
"--elk",
|
|
106
|
+
action="store_true",
|
|
107
|
+
help="Use ELK layout engine (better node placement for large diagrams)",
|
|
108
|
+
)
|
|
109
|
+
parser.add_argument(
|
|
110
|
+
"-v",
|
|
111
|
+
"--verbose",
|
|
112
|
+
action="store_true",
|
|
113
|
+
help="Verbose logging",
|
|
114
|
+
)
|
|
115
|
+
return parser.parse_args(args)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _expand_targets(targets_str: str) -> list[str]:
|
|
119
|
+
"""Expand comma-separated targets (IPs, CIDR, ranges) into a flat list."""
|
|
120
|
+
result: list[str] = []
|
|
121
|
+
for part in targets_str.split(","):
|
|
122
|
+
part = part.strip()
|
|
123
|
+
if not part:
|
|
124
|
+
continue
|
|
125
|
+
if "/" in part:
|
|
126
|
+
# CIDR notation: 192.168.101.0/24
|
|
127
|
+
try:
|
|
128
|
+
net = ipaddress.IPv4Network(part, strict=False)
|
|
129
|
+
result.extend(str(ip) for ip in net.hosts())
|
|
130
|
+
except ValueError:
|
|
131
|
+
logger.warning(f"Invalid CIDR target: {part}")
|
|
132
|
+
elif "-" in part.rsplit(".", 1)[-1]:
|
|
133
|
+
# Last-octet range: 192.168.101.1-254
|
|
134
|
+
prefix, last = part.rsplit(".", 1)
|
|
135
|
+
try:
|
|
136
|
+
start_s, end_s = last.split("-", 1)
|
|
137
|
+
start, end = int(start_s), int(end_s)
|
|
138
|
+
result.extend(f"{prefix}.{i}" for i in range(start, end + 1))
|
|
139
|
+
except ValueError, TypeError:
|
|
140
|
+
logger.warning(f"Invalid range target: {part}")
|
|
141
|
+
else:
|
|
142
|
+
result.append(part)
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _parse_switches(switches_str: str) -> list[tuple[str, str]]:
|
|
147
|
+
"""Parse --switches argument: IP[:COMMUNITY],..."""
|
|
148
|
+
switches: list[tuple[str, str]] = []
|
|
149
|
+
for part in switches_str.split(","):
|
|
150
|
+
part = part.strip()
|
|
151
|
+
if not part:
|
|
152
|
+
continue
|
|
153
|
+
if ":" in part:
|
|
154
|
+
ip, community = part.split(":", 1)
|
|
155
|
+
else:
|
|
156
|
+
ip, community = part, "public"
|
|
157
|
+
switches.append((ip, community))
|
|
158
|
+
return switches
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _parse_topology(topology_str: str) -> list[tuple[str, str, str]]:
|
|
162
|
+
"""Parse --topology argument: HOST_IP:SWITCH_IP:PORT_NAME,..."""
|
|
163
|
+
entries: list[tuple[str, str, str]] = []
|
|
164
|
+
for entry in topology_str.split(","):
|
|
165
|
+
entry = entry.strip()
|
|
166
|
+
if not entry:
|
|
167
|
+
continue
|
|
168
|
+
parts = entry.split(":", 2)
|
|
169
|
+
if len(parts) != 3:
|
|
170
|
+
logger.warning(f"Invalid --topology entry (need HOST:SWITCH:PORT): {entry}")
|
|
171
|
+
continue
|
|
172
|
+
entries.append((parts[0], parts[1], parts[2]))
|
|
173
|
+
return entries
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def main(args: list[str] | None = None) -> None:
|
|
177
|
+
"""Main entry point for discovery CLI."""
|
|
178
|
+
parsed = parse_args(args)
|
|
179
|
+
|
|
180
|
+
if not parsed.verbose:
|
|
181
|
+
logger.remove()
|
|
182
|
+
logger.add(sys.stderr, level="INFO")
|
|
183
|
+
|
|
184
|
+
traceroute_targets: list[str] = []
|
|
185
|
+
if parsed.targets:
|
|
186
|
+
traceroute_targets = _expand_targets(parsed.targets)
|
|
187
|
+
|
|
188
|
+
interfaces = [i.strip() for i in parsed.interface.split(",") if i.strip()] if parsed.interface else []
|
|
189
|
+
|
|
190
|
+
# Parse --switches
|
|
191
|
+
switches: list[tuple[str, str]] = []
|
|
192
|
+
if parsed.switches:
|
|
193
|
+
if not HAS_PYSNMP:
|
|
194
|
+
logger.error("pysnmp is required for --switches (pip install pysnmp)")
|
|
195
|
+
sys.exit(1)
|
|
196
|
+
switches = _parse_switches(parsed.switches)
|
|
197
|
+
|
|
198
|
+
scanner = NetworkTopologyScanner(
|
|
199
|
+
interfaces=interfaces,
|
|
200
|
+
use_nmap=parsed.nmap,
|
|
201
|
+
top_ports=parsed.top_ports,
|
|
202
|
+
timeout=parsed.timeout,
|
|
203
|
+
max_hops=parsed.max_hops,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Parse --topology
|
|
207
|
+
manual_topology: list[tuple[str, str, str]] = []
|
|
208
|
+
if parsed.topology:
|
|
209
|
+
manual_topology = _parse_topology(parsed.topology)
|
|
210
|
+
|
|
211
|
+
topology = scanner.run_discovery(
|
|
212
|
+
traceroute_targets=traceroute_targets,
|
|
213
|
+
trace_local=parsed.trace_local,
|
|
214
|
+
switches=switches,
|
|
215
|
+
lldp_collect_dir=Path(parsed.lldp_collect) if parsed.lldp_collect else None,
|
|
216
|
+
lldp_dir=Path(parsed.lldp_dir) if parsed.lldp_dir else None,
|
|
217
|
+
manual_topology=manual_topology or None,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
if parsed.format == "json":
|
|
221
|
+
output = topology.model_dump_json(indent=2)
|
|
222
|
+
else:
|
|
223
|
+
generator = MermaidGenerator(
|
|
224
|
+
topology,
|
|
225
|
+
direction=parsed.direction,
|
|
226
|
+
diagram_style=parsed.diagram_style,
|
|
227
|
+
elk=parsed.elk,
|
|
228
|
+
)
|
|
229
|
+
output = generator.generate()
|
|
230
|
+
|
|
231
|
+
if parsed.output:
|
|
232
|
+
Path(parsed.output).write_text(output + "\n")
|
|
233
|
+
logger.info(f"Output written to {parsed.output}")
|
|
234
|
+
else:
|
|
235
|
+
print(output)
|