first commit
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""LibreNet Scanner - scanner réseau graphique libre pour Linux."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,3 @@
|
||||
from .main import main
|
||||
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from .models import Host
|
||||
|
||||
|
||||
def export_csv(path: str | Path, hosts: list[Host]) -> None:
|
||||
with open(path, "w", encoding="utf-8", newline="") as handle:
|
||||
writer = csv.writer(handle)
|
||||
writer.writerow(["status", "hostname", "ip", "mac", "vendor", "ports", "os", "latency_ms", "last_seen"])
|
||||
for host in hosts:
|
||||
writer.writerow([
|
||||
host.status,
|
||||
host.hostname,
|
||||
host.ip,
|
||||
host.mac,
|
||||
host.vendor,
|
||||
host.ports_summary,
|
||||
host.os_name,
|
||||
"" if host.latency_ms is None else f"{host.latency_ms:.2f}",
|
||||
host.last_seen,
|
||||
])
|
||||
|
||||
|
||||
def export_json(path: str | Path, hosts: list[Host]) -> None:
|
||||
payload = []
|
||||
for host in hosts:
|
||||
payload.append({
|
||||
"status": host.status,
|
||||
"hostname": host.hostname,
|
||||
"ip": host.ip,
|
||||
"mac": host.mac,
|
||||
"vendor": host.vendor,
|
||||
"os": host.os_name,
|
||||
"latency_ms": host.latency_ms,
|
||||
"last_seen": host.last_seen,
|
||||
"ports": [
|
||||
{
|
||||
"port": p.port,
|
||||
"protocol": p.protocol,
|
||||
"service": p.service,
|
||||
"product": p.product,
|
||||
"version": p.version,
|
||||
}
|
||||
for p in host.ports
|
||||
],
|
||||
})
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump(payload, handle, ensure_ascii=False, indent=2)
|
||||
@@ -0,0 +1,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from .ui import MainWindow
|
||||
|
||||
|
||||
def main() -> int:
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName("LibreNet Scanner")
|
||||
app.setOrganizationName("LibreNet")
|
||||
icon = QIcon.fromTheme("network-wired")
|
||||
if not icon.isNull():
|
||||
app.setWindowIcon(icon)
|
||||
window = MainWindow()
|
||||
window.show()
|
||||
return app.exec()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,62 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PortInfo:
|
||||
port: int
|
||||
protocol: str = "tcp"
|
||||
state: str = "open"
|
||||
service: str = ""
|
||||
product: str = ""
|
||||
version: str = ""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
service = self.service or "?"
|
||||
return f"{self.port}/{self.protocol} {service}" if service else f"{self.port}/{self.protocol}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Host:
|
||||
ip: str
|
||||
hostname: str = ""
|
||||
mac: str = ""
|
||||
vendor: str = ""
|
||||
status: str = "up"
|
||||
os_name: str = ""
|
||||
latency_ms: float | None = None
|
||||
ports: list[PortInfo] = field(default_factory=list)
|
||||
last_seen: str = field(default_factory=lambda: datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds"))
|
||||
|
||||
def merge(self, other: "Host") -> "Host":
|
||||
if other.hostname:
|
||||
self.hostname = other.hostname
|
||||
if other.mac:
|
||||
self.mac = other.mac.upper()
|
||||
if other.vendor:
|
||||
self.vendor = other.vendor
|
||||
if other.os_name:
|
||||
self.os_name = other.os_name
|
||||
if other.latency_ms is not None:
|
||||
self.latency_ms = other.latency_ms
|
||||
if other.ports:
|
||||
known = {(p.port, p.protocol): p for p in self.ports}
|
||||
for port in other.ports:
|
||||
known[(port.port, port.protocol)] = port
|
||||
self.ports = sorted(known.values(), key=lambda p: (p.protocol, p.port))
|
||||
self.status = other.status or self.status
|
||||
self.last_seen = other.last_seen or self.last_seen
|
||||
return self
|
||||
|
||||
@property
|
||||
def ports_summary(self) -> str:
|
||||
if not self.ports:
|
||||
return ""
|
||||
return ", ".join(
|
||||
f"{p.port}/{p.protocol}" + (f" ({p.service})" if p.service else "")
|
||||
for p in self.ports
|
||||
if p.state == "open"
|
||||
)
|
||||
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
VIRTUAL_PREFIXES = (
|
||||
"lo", "docker", "br-", "veth", "virbr", "podman", "cni", "flannel", "tun", "tap",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class NetworkInterface:
|
||||
name: str
|
||||
address: str
|
||||
prefixlen: int
|
||||
network: str
|
||||
is_virtual: bool = False
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
suffix = " (virtuelle)" if self.is_virtual else ""
|
||||
return f"{self.name} — {self.address}/{self.prefixlen} — {self.network}{suffix}"
|
||||
|
||||
|
||||
def validate_target(value: str) -> str:
|
||||
value = value.strip()
|
||||
try:
|
||||
if "/" in value:
|
||||
return str(ipaddress.ip_network(value, strict=False))
|
||||
return str(ipaddress.ip_address(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Cible IPv4 invalide : {value}") from exc
|
||||
|
||||
|
||||
def list_ipv4_interfaces() -> list[NetworkInterface]:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["ip", "-j", "-4", "addr", "show", "up"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
payload = json.loads(proc.stdout)
|
||||
except (OSError, subprocess.SubprocessError, json.JSONDecodeError):
|
||||
return []
|
||||
|
||||
result: list[NetworkInterface] = []
|
||||
for item in payload:
|
||||
name = item.get("ifname", "")
|
||||
if not name or name == "lo":
|
||||
continue
|
||||
virtual = name.startswith(VIRTUAL_PREFIXES)
|
||||
for addr in item.get("addr_info", []):
|
||||
if addr.get("family") != "inet" or addr.get("scope") != "global":
|
||||
continue
|
||||
local = addr.get("local")
|
||||
prefixlen = int(addr.get("prefixlen", 32))
|
||||
if not local:
|
||||
continue
|
||||
network = str(ipaddress.ip_network(f"{local}/{prefixlen}", strict=False))
|
||||
result.append(NetworkInterface(name, local, prefixlen, network, virtual))
|
||||
result.sort(key=lambda i: (i.is_virtual, i.name, i.address))
|
||||
return result
|
||||
|
||||
|
||||
def target_is_on_interface(target: str, interface: NetworkInterface | None) -> bool:
|
||||
if interface is None:
|
||||
return False
|
||||
try:
|
||||
iface_net = ipaddress.ip_network(interface.network, strict=False)
|
||||
target_net = ipaddress.ip_network(target, strict=False) if "/" in target else ipaddress.ip_network(f"{target}/32")
|
||||
return target_net.subnet_of(iface_net)
|
||||
except ValueError:
|
||||
return False
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .models import Host, PortInfo
|
||||
|
||||
|
||||
ARP_LINE = re.compile(
|
||||
r"^(?P<ip>(?:\d{1,3}\.){3}\d{1,3})\s+"
|
||||
r"(?P<mac>(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})"
|
||||
r"(?:\s+(?P<vendor>.*?))?\s*$"
|
||||
)
|
||||
|
||||
|
||||
def parse_arp_scan(text: str) -> list[Host]:
|
||||
hosts: list[Host] = []
|
||||
for raw in text.splitlines():
|
||||
match = ARP_LINE.match(raw.strip())
|
||||
if not match:
|
||||
continue
|
||||
vendor = (match.group("vendor") or "").strip()
|
||||
if vendor == "(Unknown)":
|
||||
vendor = ""
|
||||
hosts.append(
|
||||
Host(
|
||||
ip=match.group("ip"),
|
||||
mac=match.group("mac").upper(),
|
||||
vendor=vendor,
|
||||
status="up",
|
||||
)
|
||||
)
|
||||
return hosts
|
||||
|
||||
|
||||
def _address(host_node: ET.Element, kind: str) -> tuple[str, str]:
|
||||
for addr in host_node.findall("address"):
|
||||
if addr.get("addrtype") == kind:
|
||||
return addr.get("addr", ""), addr.get("vendor", "")
|
||||
return "", ""
|
||||
|
||||
|
||||
def _latency(host_node: ET.Element) -> float | None:
|
||||
times = host_node.find("times")
|
||||
if times is None:
|
||||
return None
|
||||
srtt = times.get("srtt")
|
||||
if not srtt:
|
||||
return None
|
||||
try:
|
||||
return int(srtt) / 1000.0
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def parse_nmap_xml(text: str) -> list[Host]:
|
||||
if not text.strip():
|
||||
return []
|
||||
root = ET.fromstring(text)
|
||||
hosts: list[Host] = []
|
||||
now = datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
|
||||
|
||||
for node in root.findall("host"):
|
||||
status_node = node.find("status")
|
||||
status = status_node.get("state", "unknown") if status_node is not None else "unknown"
|
||||
if status not in {"up", "unknown"}:
|
||||
continue
|
||||
|
||||
ip, _ = _address(node, "ipv4")
|
||||
if not ip:
|
||||
continue
|
||||
mac, vendor = _address(node, "mac")
|
||||
|
||||
hostname = ""
|
||||
hostnames = node.find("hostnames")
|
||||
if hostnames is not None:
|
||||
candidate = hostnames.find("hostname")
|
||||
if candidate is not None:
|
||||
hostname = candidate.get("name", "")
|
||||
|
||||
os_name = ""
|
||||
os_node = node.find("os")
|
||||
if os_node is not None:
|
||||
match = os_node.find("osmatch")
|
||||
if match is not None:
|
||||
os_name = match.get("name", "")
|
||||
|
||||
ports: list[PortInfo] = []
|
||||
ports_node = node.find("ports")
|
||||
if ports_node is not None:
|
||||
for pnode in ports_node.findall("port"):
|
||||
state_node = pnode.find("state")
|
||||
state = state_node.get("state", "") if state_node is not None else ""
|
||||
if state != "open":
|
||||
continue
|
||||
service_node = pnode.find("service")
|
||||
ports.append(
|
||||
PortInfo(
|
||||
port=int(pnode.get("portid", "0")),
|
||||
protocol=pnode.get("protocol", "tcp"),
|
||||
state=state,
|
||||
service=service_node.get("name", "") if service_node is not None else "",
|
||||
product=service_node.get("product", "") if service_node is not None else "",
|
||||
version=service_node.get("version", "") if service_node is not None else "",
|
||||
)
|
||||
)
|
||||
|
||||
hosts.append(
|
||||
Host(
|
||||
ip=ip,
|
||||
hostname=hostname,
|
||||
mac=mac.upper(),
|
||||
vendor=vendor,
|
||||
status=status,
|
||||
os_name=os_name,
|
||||
latency_ms=_latency(node),
|
||||
ports=ports,
|
||||
last_seen=now,
|
||||
)
|
||||
)
|
||||
return hosts
|
||||
@@ -0,0 +1,174 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
|
||||
from PySide6.QtCore import QThread, Signal
|
||||
|
||||
from .models import Host
|
||||
from .network import NetworkInterface, target_is_on_interface
|
||||
from .parsers import parse_arp_scan, parse_nmap_xml
|
||||
|
||||
|
||||
COMMON_PORTS = "22,23,53,80,139,443,445,3389,5900,8006,8080,8443,9100"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ScanRequest:
|
||||
target: str
|
||||
profile: str
|
||||
interface: NetworkInterface | None = None
|
||||
|
||||
|
||||
class ScanWorker(QThread):
|
||||
progress = Signal(str)
|
||||
hosts_found = Signal(object)
|
||||
failed = Signal(str)
|
||||
completed = Signal()
|
||||
|
||||
def __init__(self, request: ScanRequest, parent=None) -> None:
|
||||
super().__init__(parent)
|
||||
self.request = request
|
||||
self._proc: subprocess.Popen[str] | None = None
|
||||
|
||||
def stop(self) -> None:
|
||||
self.requestInterruption()
|
||||
proc = self._proc
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
|
||||
def _run_command(self, args: list[str], label: str) -> tuple[int, str, str]:
|
||||
if self.isInterruptionRequested():
|
||||
return 130, "", "Interrompu"
|
||||
self.progress.emit(label)
|
||||
try:
|
||||
self._proc = subprocess.Popen(
|
||||
args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
stdout, stderr = self._proc.communicate()
|
||||
return self._proc.returncode or 0, stdout, stderr
|
||||
except FileNotFoundError:
|
||||
return 127, "", f"Commande introuvable : {args[0]}"
|
||||
except OSError as exc:
|
||||
return 1, "", str(exc)
|
||||
finally:
|
||||
self._proc = None
|
||||
|
||||
def _arp_scan_command(self) -> str | None:
|
||||
found = shutil.which("arp-scan")
|
||||
if found:
|
||||
return found
|
||||
for candidate in ("/usr/sbin/arp-scan", "/usr/bin/arp-scan"):
|
||||
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
def _emit_arp(self) -> bool:
|
||||
command = self._arp_scan_command()
|
||||
if not command:
|
||||
return False
|
||||
iface = self.request.interface
|
||||
if not iface or not target_is_on_interface(self.request.target, iface):
|
||||
return False
|
||||
args = [command, "--interface", iface.name, self.request.target]
|
||||
code, stdout, stderr = self._run_command(args, "Découverte ARP…")
|
||||
# arp-scan peut retourner 1 si aucun hôte n'est trouvé : on ne bloque pas le scan Nmap.
|
||||
hosts = parse_arp_scan(stdout)
|
||||
if hosts:
|
||||
self.hosts_found.emit(hosts)
|
||||
if code not in (0, 1) and stderr:
|
||||
self.progress.emit(f"arp-scan indisponible sans privilèges, repli Nmap : {stderr.strip().splitlines()[-1]}")
|
||||
return bool(hosts)
|
||||
|
||||
def _nmap(self, args: list[str], label: str) -> list[Host]:
|
||||
code, stdout, stderr = self._run_command(args, label)
|
||||
if self.isInterruptionRequested():
|
||||
return []
|
||||
if code != 0:
|
||||
raise RuntimeError(stderr.strip() or f"Nmap a quitté avec le code {code}")
|
||||
return parse_nmap_xml(stdout)
|
||||
|
||||
def run(self) -> None:
|
||||
try:
|
||||
profile = self.request.profile
|
||||
target = self.request.target
|
||||
|
||||
if profile == "Rapide":
|
||||
arp_ok = self._emit_arp()
|
||||
if not arp_ok:
|
||||
hosts = self._nmap(["nmap", "-sn", "-oX", "-", target], "Découverte Nmap…")
|
||||
if hosts:
|
||||
self.hosts_found.emit(hosts)
|
||||
|
||||
elif profile == "Standard":
|
||||
self._emit_arp()
|
||||
hosts = self._nmap(["nmap", "-sn", "-oX", "-", target], "Découverte des hôtes…")
|
||||
if hosts:
|
||||
self.hosts_found.emit(hosts)
|
||||
if self.isInterruptionRequested():
|
||||
return
|
||||
ips = [h.ip for h in hosts]
|
||||
if ips:
|
||||
args = ["nmap", "-Pn", "-sT", "--open", "-T4", "-p", COMMON_PORTS, "-oX", "-", *ips]
|
||||
port_hosts = self._nmap(args, "Scan des ports usuels…")
|
||||
if port_hosts:
|
||||
self.hosts_found.emit(port_hosts)
|
||||
|
||||
elif profile == "Approfondi":
|
||||
self._emit_arp()
|
||||
args = ["nmap", "-sT", "-sV", "--version-light", "--open", "-T4", "--top-ports", "100", "-oX", "-", target]
|
||||
hosts = self._nmap(args, "Scan approfondi : services et 100 ports principaux…")
|
||||
if hosts:
|
||||
self.hosts_found.emit(hosts)
|
||||
else:
|
||||
raise RuntimeError(f"Profil inconnu : {profile}")
|
||||
|
||||
except Exception as exc: # frontière thread -> GUI
|
||||
self.failed.emit(str(exc))
|
||||
finally:
|
||||
self.completed.emit()
|
||||
|
||||
|
||||
class HostScanWorker(QThread):
|
||||
progress = Signal(str)
|
||||
result = Signal(object)
|
||||
failed = Signal(str)
|
||||
completed = Signal()
|
||||
|
||||
def __init__(self, ip: str, parent=None) -> None:
|
||||
super().__init__(parent)
|
||||
self.ip = str(ipaddress.ip_address(ip))
|
||||
self._proc: subprocess.Popen[str] | None = None
|
||||
|
||||
def stop(self) -> None:
|
||||
self.requestInterruption()
|
||||
if self._proc and self._proc.poll() is None:
|
||||
self._proc.terminate()
|
||||
|
||||
def run(self) -> None:
|
||||
self.progress.emit(f"Scan détaillé de {self.ip}…")
|
||||
args = ["nmap", "-sT", "-sV", "--version-light", "--open", "-T4", "--top-ports", "1000", "-oX", "-", self.ip]
|
||||
try:
|
||||
self._proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")
|
||||
stdout, stderr = self._proc.communicate()
|
||||
if self.isInterruptionRequested():
|
||||
return
|
||||
if self._proc.returncode != 0:
|
||||
self.failed.emit(stderr.strip() or f"Nmap a quitté avec le code {self._proc.returncode}")
|
||||
return
|
||||
hosts = parse_nmap_xml(stdout)
|
||||
if hosts:
|
||||
self.result.emit(hosts[0])
|
||||
except OSError as exc:
|
||||
self.failed.emit(str(exc))
|
||||
finally:
|
||||
self._proc = None
|
||||
self.completed.emit()
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from .models import Host
|
||||
|
||||
|
||||
def data_dir() -> Path:
|
||||
root = os.environ.get("XDG_DATA_HOME")
|
||||
if root:
|
||||
path = Path(root) / "librenet-scanner"
|
||||
else:
|
||||
path = Path.home() / ".local" / "share" / "librenet-scanner"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
class HistoryStore:
|
||||
def __init__(self, db_path: Path | None = None) -> None:
|
||||
self.db_path = db_path or data_dir() / "history.sqlite3"
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def _init_db(self) -> None:
|
||||
with self._connect() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
PRAGMA journal_mode=WAL;
|
||||
CREATE TABLE IF NOT EXISTS scans (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
host_count INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS scan_hosts (
|
||||
scan_id INTEGER NOT NULL,
|
||||
ip TEXT NOT NULL,
|
||||
hostname TEXT,
|
||||
mac TEXT,
|
||||
vendor TEXT,
|
||||
os_name TEXT,
|
||||
ports_json TEXT NOT NULL,
|
||||
FOREIGN KEY(scan_id) REFERENCES scans(id) ON DELETE CASCADE
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
def save_scan(self, target: str, profile: str, hosts: list[Host]) -> int:
|
||||
now = datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO scans(created_at, target, profile, host_count) VALUES (?, ?, ?, ?)",
|
||||
(now, target, profile, len(hosts)),
|
||||
)
|
||||
scan_id = int(cur.lastrowid)
|
||||
for host in hosts:
|
||||
ports = [
|
||||
{
|
||||
"port": p.port,
|
||||
"protocol": p.protocol,
|
||||
"service": p.service,
|
||||
"product": p.product,
|
||||
"version": p.version,
|
||||
}
|
||||
for p in host.ports
|
||||
]
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO scan_hosts(scan_id, ip, hostname, mac, vendor, os_name, ports_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(scan_id, host.ip, host.hostname, host.mac, host.vendor, host.os_name, json.dumps(ports, ensure_ascii=False)),
|
||||
)
|
||||
return scan_id
|
||||
|
||||
def recent_scans(self, limit: int = 100) -> list[sqlite3.Row]:
|
||||
with self._connect() as conn:
|
||||
return list(
|
||||
conn.execute(
|
||||
"SELECT id, created_at, target, profile, host_count FROM scans ORDER BY id DESC LIMIT ?",
|
||||
(limit,),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,425 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt, QUrl
|
||||
from PySide6.QtGui import QAction, QColor, QDesktopServices, QIcon
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QApplication,
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QHeaderView,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMainWindow,
|
||||
QMenu,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QStatusBar,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .exporters import export_csv, export_json
|
||||
from .models import Host
|
||||
from .network import NetworkInterface, list_ipv4_interfaces, validate_target
|
||||
from .scanner import HostScanWorker, ScanRequest, ScanWorker
|
||||
from .storage import HistoryStore
|
||||
|
||||
|
||||
COL_STATUS = 0
|
||||
COL_HOSTNAME = 1
|
||||
COL_IP = 2
|
||||
COL_MAC = 3
|
||||
COL_VENDOR = 4
|
||||
COL_PORTS = 5
|
||||
COL_OS = 6
|
||||
COL_LATENCY = 7
|
||||
COL_LAST = 8
|
||||
|
||||
|
||||
class HistoryDialog(QDialog):
|
||||
def __init__(self, store: HistoryStore, parent=None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Historique des scans")
|
||||
self.resize(780, 420)
|
||||
layout = QVBoxLayout(self)
|
||||
table = QTableWidget(0, 5, self)
|
||||
table.setHorizontalHeaderLabels(["Date", "Cible", "Profil", "Hôtes", "ID"])
|
||||
table.setEditTriggers(QAbstractItemView.NoEditTriggers)
|
||||
table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
||||
rows = store.recent_scans()
|
||||
table.setRowCount(len(rows))
|
||||
for row_idx, row in enumerate(rows):
|
||||
values = [row["created_at"], row["target"], row["profile"], str(row["host_count"]), str(row["id"])]
|
||||
for col, value in enumerate(values):
|
||||
table.setItem(row_idx, col, QTableWidgetItem(value))
|
||||
table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
|
||||
table.horizontalHeader().setStretchLastSection(True)
|
||||
layout.addWidget(table)
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.setWindowTitle("LibreNet Scanner 0.1.0")
|
||||
self.resize(1220, 700)
|
||||
self.hosts: dict[str, Host] = {}
|
||||
self.interfaces: list[NetworkInterface] = []
|
||||
self.worker: ScanWorker | None = None
|
||||
self.host_worker: HostScanWorker | None = None
|
||||
self.store = HistoryStore()
|
||||
|
||||
self._build_ui()
|
||||
self._build_menu()
|
||||
self.refresh_interfaces()
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
central = QWidget(self)
|
||||
outer = QVBoxLayout(central)
|
||||
|
||||
top = QHBoxLayout()
|
||||
self.interface_combo = QComboBox()
|
||||
self.interface_combo.setMinimumWidth(350)
|
||||
self.interface_combo.currentIndexChanged.connect(self._interface_changed)
|
||||
self.target_edit = QLineEdit()
|
||||
self.target_edit.setPlaceholderText("192.168.1.0/24")
|
||||
self.target_edit.setMinimumWidth(180)
|
||||
self.profile_combo = QComboBox()
|
||||
self.profile_combo.addItems(["Rapide", "Standard", "Approfondi"])
|
||||
self.scan_btn = QPushButton("▶ Scanner")
|
||||
self.scan_btn.clicked.connect(self.start_scan)
|
||||
self.stop_btn = QPushButton("■ Stop")
|
||||
self.stop_btn.setEnabled(False)
|
||||
self.stop_btn.clicked.connect(self.stop_scan)
|
||||
|
||||
top.addWidget(QLabel("Interface :"))
|
||||
top.addWidget(self.interface_combo, 2)
|
||||
top.addWidget(QLabel("Réseau / cible :"))
|
||||
top.addWidget(self.target_edit, 1)
|
||||
top.addWidget(QLabel("Profil :"))
|
||||
top.addWidget(self.profile_combo)
|
||||
top.addWidget(self.scan_btn)
|
||||
top.addWidget(self.stop_btn)
|
||||
outer.addLayout(top)
|
||||
|
||||
self.table = QTableWidget(0, 9)
|
||||
self.table.setHorizontalHeaderLabels([
|
||||
"État", "Nom", "IP", "MAC", "Constructeur", "Ports / services", "OS", "Latence", "Dernière vue"
|
||||
])
|
||||
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
||||
self.table.setSelectionMode(QAbstractItemView.SingleSelection)
|
||||
self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
|
||||
self.table.setSortingEnabled(True)
|
||||
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
self.table.customContextMenuRequested.connect(self._context_menu)
|
||||
self.table.itemDoubleClicked.connect(lambda _item: self.scan_selected_host())
|
||||
header = self.table.horizontalHeader()
|
||||
header.setSectionResizeMode(QHeaderView.Interactive)
|
||||
header.setStretchLastSection(True)
|
||||
self.table.setColumnWidth(COL_STATUS, 60)
|
||||
self.table.setColumnWidth(COL_HOSTNAME, 170)
|
||||
self.table.setColumnWidth(COL_IP, 125)
|
||||
self.table.setColumnWidth(COL_MAC, 150)
|
||||
self.table.setColumnWidth(COL_VENDOR, 190)
|
||||
self.table.setColumnWidth(COL_PORTS, 280)
|
||||
outer.addWidget(self.table, 1)
|
||||
|
||||
bottom = QHBoxLayout()
|
||||
self.summary_label = QLabel("0 hôte")
|
||||
self.activity_label = QLabel("Prêt")
|
||||
bottom.addWidget(self.summary_label)
|
||||
bottom.addStretch(1)
|
||||
bottom.addWidget(self.activity_label)
|
||||
outer.addLayout(bottom)
|
||||
|
||||
self.setCentralWidget(central)
|
||||
self.setStatusBar(QStatusBar())
|
||||
|
||||
def _build_menu(self) -> None:
|
||||
file_menu = self.menuBar().addMenu("Fichier")
|
||||
export_csv_action = QAction("Exporter CSV…", self)
|
||||
export_csv_action.triggered.connect(self.export_csv_dialog)
|
||||
export_json_action = QAction("Exporter JSON…", self)
|
||||
export_json_action.triggered.connect(self.export_json_dialog)
|
||||
quit_action = QAction("Quitter", self)
|
||||
quit_action.triggered.connect(self.close)
|
||||
file_menu.addAction(export_csv_action)
|
||||
file_menu.addAction(export_json_action)
|
||||
file_menu.addSeparator()
|
||||
file_menu.addAction(quit_action)
|
||||
|
||||
scan_menu = self.menuBar().addMenu("Scan")
|
||||
refresh_action = QAction("Rafraîchir les interfaces", self)
|
||||
refresh_action.triggered.connect(self.refresh_interfaces)
|
||||
history_action = QAction("Historique…", self)
|
||||
history_action.triggered.connect(self.show_history)
|
||||
clear_action = QAction("Vider les résultats", self)
|
||||
clear_action.triggered.connect(self.clear_results)
|
||||
scan_menu.addAction(refresh_action)
|
||||
scan_menu.addAction(history_action)
|
||||
scan_menu.addAction(clear_action)
|
||||
|
||||
help_menu = self.menuBar().addMenu("Aide")
|
||||
about_action = QAction("À propos", self)
|
||||
about_action.triggered.connect(self.show_about)
|
||||
help_menu.addAction(about_action)
|
||||
|
||||
def refresh_interfaces(self) -> None:
|
||||
self.interfaces = list_ipv4_interfaces()
|
||||
self.interface_combo.blockSignals(True)
|
||||
self.interface_combo.clear()
|
||||
visible = [i for i in self.interfaces if not i.is_virtual]
|
||||
if not visible:
|
||||
visible = self.interfaces
|
||||
for iface in visible:
|
||||
self.interface_combo.addItem(iface.label, iface)
|
||||
self.interface_combo.blockSignals(False)
|
||||
if self.interface_combo.count():
|
||||
self.interface_combo.setCurrentIndex(0)
|
||||
self._interface_changed(0)
|
||||
elif not self.target_edit.text():
|
||||
self.target_edit.setText("192.168.1.0/24")
|
||||
self.statusBar().showMessage(f"{len(visible)} interface(s) IPv4 détectée(s)", 4000)
|
||||
|
||||
def _interface_changed(self, index: int) -> None:
|
||||
iface = self.interface_combo.itemData(index)
|
||||
if isinstance(iface, NetworkInterface):
|
||||
self.target_edit.setText(iface.network)
|
||||
|
||||
def selected_interface(self) -> NetworkInterface | None:
|
||||
data = self.interface_combo.currentData()
|
||||
return data if isinstance(data, NetworkInterface) else None
|
||||
|
||||
def start_scan(self) -> None:
|
||||
if self.worker and self.worker.isRunning():
|
||||
return
|
||||
try:
|
||||
target = validate_target(self.target_edit.text())
|
||||
except ValueError as exc:
|
||||
QMessageBox.warning(self, "Cible invalide", str(exc))
|
||||
return
|
||||
# Protection simple contre un scan accidentel gigantesque.
|
||||
if "/" in target:
|
||||
net = ipaddress.ip_network(target, strict=False)
|
||||
if net.num_addresses > 4096:
|
||||
QMessageBox.warning(self, "Réseau trop grand", "La V0.1 limite un scan à 4096 adresses (jusqu'à /20 en IPv4).")
|
||||
return
|
||||
|
||||
profile = self.profile_combo.currentText()
|
||||
self.hosts.clear()
|
||||
self.table.setSortingEnabled(False)
|
||||
self.table.setRowCount(0)
|
||||
self.table.setSortingEnabled(True)
|
||||
request = ScanRequest(target=target, profile=profile, interface=self.selected_interface())
|
||||
self.worker = ScanWorker(request, self)
|
||||
self.worker.progress.connect(self._progress)
|
||||
self.worker.hosts_found.connect(self._merge_hosts)
|
||||
self.worker.failed.connect(self._scan_failed)
|
||||
self.worker.completed.connect(lambda: self._scan_finished(target, profile))
|
||||
self.scan_btn.setEnabled(False)
|
||||
self.stop_btn.setEnabled(True)
|
||||
self.activity_label.setText("Démarrage…")
|
||||
self.worker.start()
|
||||
|
||||
def stop_scan(self) -> None:
|
||||
if self.worker and self.worker.isRunning():
|
||||
self.worker.stop()
|
||||
self.activity_label.setText("Arrêt demandé…")
|
||||
if self.host_worker and self.host_worker.isRunning():
|
||||
self.host_worker.stop()
|
||||
|
||||
def _progress(self, message: str) -> None:
|
||||
self.activity_label.setText(message)
|
||||
self.statusBar().showMessage(message)
|
||||
|
||||
def _merge_hosts(self, incoming: list[Host]) -> None:
|
||||
for host in incoming:
|
||||
existing = self.hosts.get(host.ip)
|
||||
if existing:
|
||||
existing.merge(host)
|
||||
else:
|
||||
self.hosts[host.ip] = host
|
||||
self._refresh_table()
|
||||
|
||||
def _refresh_table(self) -> None:
|
||||
selected_ip = self._selected_ip()
|
||||
self.table.setSortingEnabled(False)
|
||||
self.table.setRowCount(0)
|
||||
for host in sorted(self.hosts.values(), key=lambda h: ipaddress.ip_address(h.ip)):
|
||||
row = self.table.rowCount()
|
||||
self.table.insertRow(row)
|
||||
status = QTableWidgetItem("●" if host.status == "up" else "○")
|
||||
status.setTextAlignment(Qt.AlignCenter)
|
||||
if host.status == "up":
|
||||
status.setForeground(QColor("#2e7d32"))
|
||||
self.table.setItem(row, COL_STATUS, status)
|
||||
self.table.setItem(row, COL_HOSTNAME, QTableWidgetItem(host.hostname))
|
||||
ip_item = QTableWidgetItem(host.ip)
|
||||
ip_item.setData(Qt.UserRole, host.ip)
|
||||
self.table.setItem(row, COL_IP, ip_item)
|
||||
self.table.setItem(row, COL_MAC, QTableWidgetItem(host.mac))
|
||||
self.table.setItem(row, COL_VENDOR, QTableWidgetItem(host.vendor))
|
||||
self.table.setItem(row, COL_PORTS, QTableWidgetItem(host.ports_summary))
|
||||
self.table.setItem(row, COL_OS, QTableWidgetItem(host.os_name))
|
||||
latency = "" if host.latency_ms is None else f"{host.latency_ms:.1f} ms"
|
||||
self.table.setItem(row, COL_LATENCY, QTableWidgetItem(latency))
|
||||
self.table.setItem(row, COL_LAST, QTableWidgetItem(host.last_seen))
|
||||
if selected_ip == host.ip:
|
||||
self.table.selectRow(row)
|
||||
self.table.setSortingEnabled(True)
|
||||
self.summary_label.setText(f"{len(self.hosts)} hôte(s) actif(s)")
|
||||
|
||||
def _scan_failed(self, message: str) -> None:
|
||||
QMessageBox.critical(self, "Erreur de scan", message)
|
||||
self.activity_label.setText("Erreur")
|
||||
|
||||
def _scan_finished(self, target: str, profile: str) -> None:
|
||||
self.scan_btn.setEnabled(True)
|
||||
self.stop_btn.setEnabled(False)
|
||||
if self.worker and self.worker.isInterruptionRequested():
|
||||
self.activity_label.setText("Scan interrompu")
|
||||
return
|
||||
self.activity_label.setText("Scan terminé")
|
||||
if self.hosts:
|
||||
try:
|
||||
self.store.save_scan(target, profile, list(self.hosts.values()))
|
||||
except OSError as exc:
|
||||
self.statusBar().showMessage(f"Historique non enregistré : {exc}", 5000)
|
||||
|
||||
def _selected_ip(self) -> str | None:
|
||||
row = self.table.currentRow()
|
||||
if row < 0:
|
||||
return None
|
||||
item = self.table.item(row, COL_IP)
|
||||
return item.text() if item else None
|
||||
|
||||
def _selected_host(self) -> Host | None:
|
||||
ip = self._selected_ip()
|
||||
return self.hosts.get(ip) if ip else None
|
||||
|
||||
def _context_menu(self, pos) -> None:
|
||||
item = self.table.itemAt(pos)
|
||||
if item is None:
|
||||
return
|
||||
self.table.selectRow(item.row())
|
||||
host = self._selected_host()
|
||||
if not host:
|
||||
return
|
||||
menu = QMenu(self)
|
||||
scan = menu.addAction("Scanner les ports (1000 principaux)")
|
||||
menu.addSeparator()
|
||||
http = menu.addAction("Ouvrir HTTP")
|
||||
https = menu.addAction("Ouvrir HTTPS")
|
||||
ssh = menu.addAction("Ouvrir SSH dans Konsole")
|
||||
ping = menu.addAction("Ping dans Konsole")
|
||||
smb = menu.addAction("Ouvrir SMB dans Dolphin")
|
||||
rdp = menu.addAction("Ouvrir RDP avec Remmina")
|
||||
rdp.setEnabled(shutil.which("remmina") is not None)
|
||||
menu.addSeparator()
|
||||
copy_ip = menu.addAction("Copier l'adresse IP")
|
||||
copy_mac = menu.addAction("Copier l'adresse MAC")
|
||||
copy_mac.setEnabled(bool(host.mac))
|
||||
|
||||
chosen = menu.exec(self.table.viewport().mapToGlobal(pos))
|
||||
if chosen == scan:
|
||||
self.scan_selected_host()
|
||||
elif chosen == http:
|
||||
QDesktopServices.openUrl(QUrl(f"http://{host.ip}"))
|
||||
elif chosen == https:
|
||||
QDesktopServices.openUrl(QUrl(f"https://{host.ip}"))
|
||||
elif chosen == ssh:
|
||||
self._run_terminal(["ssh", host.ip])
|
||||
elif chosen == ping:
|
||||
self._run_terminal(["ping", host.ip])
|
||||
elif chosen == smb:
|
||||
QDesktopServices.openUrl(QUrl(f"smb://{host.ip}/"))
|
||||
elif chosen == rdp:
|
||||
subprocess.Popen(["remmina", "-c", f"rdp://{host.ip}"])
|
||||
elif chosen == copy_ip:
|
||||
QApplication.clipboard().setText(host.ip)
|
||||
elif chosen == copy_mac:
|
||||
QApplication.clipboard().setText(host.mac)
|
||||
|
||||
def _run_terminal(self, command: list[str]) -> None:
|
||||
terminal = shutil.which("konsole")
|
||||
if not terminal:
|
||||
QMessageBox.warning(self, "Konsole absent", "Konsole n'est pas installé ou n'est pas dans le PATH.")
|
||||
return
|
||||
try:
|
||||
subprocess.Popen([terminal, "-e", *command])
|
||||
except OSError as exc:
|
||||
QMessageBox.critical(self, "Erreur", str(exc))
|
||||
|
||||
def scan_selected_host(self) -> None:
|
||||
host = self._selected_host()
|
||||
if not host:
|
||||
return
|
||||
if self.host_worker and self.host_worker.isRunning():
|
||||
QMessageBox.information(self, "Scan en cours", "Un scan détaillé est déjà en cours.")
|
||||
return
|
||||
self.host_worker = HostScanWorker(host.ip, self)
|
||||
self.host_worker.progress.connect(self._progress)
|
||||
self.host_worker.result.connect(self._host_scan_result)
|
||||
self.host_worker.failed.connect(lambda m: QMessageBox.critical(self, "Erreur Nmap", m))
|
||||
self.host_worker.completed.connect(lambda: self.activity_label.setText("Scan détaillé terminé"))
|
||||
self.host_worker.start()
|
||||
|
||||
def _host_scan_result(self, result: Host) -> None:
|
||||
if result.ip in self.hosts:
|
||||
self.hosts[result.ip].merge(result)
|
||||
else:
|
||||
self.hosts[result.ip] = result
|
||||
self._refresh_table()
|
||||
|
||||
def export_csv_dialog(self) -> None:
|
||||
if not self.hosts:
|
||||
QMessageBox.information(self, "Export", "Aucun résultat à exporter.")
|
||||
return
|
||||
filename, _ = QFileDialog.getSaveFileName(self, "Exporter en CSV", "librenet-scan.csv", "CSV (*.csv)")
|
||||
if filename:
|
||||
export_csv(filename, list(self.hosts.values()))
|
||||
self.statusBar().showMessage(f"Export CSV : {filename}", 5000)
|
||||
|
||||
def export_json_dialog(self) -> None:
|
||||
if not self.hosts:
|
||||
QMessageBox.information(self, "Export", "Aucun résultat à exporter.")
|
||||
return
|
||||
filename, _ = QFileDialog.getSaveFileName(self, "Exporter en JSON", "librenet-scan.json", "JSON (*.json)")
|
||||
if filename:
|
||||
export_json(filename, list(self.hosts.values()))
|
||||
self.statusBar().showMessage(f"Export JSON : {filename}", 5000)
|
||||
|
||||
def show_history(self) -> None:
|
||||
HistoryDialog(self.store, self).exec()
|
||||
|
||||
def clear_results(self) -> None:
|
||||
self.hosts.clear()
|
||||
self.table.setRowCount(0)
|
||||
self.summary_label.setText("0 hôte")
|
||||
self.activity_label.setText("Prêt")
|
||||
|
||||
def show_about(self) -> None:
|
||||
QMessageBox.about(
|
||||
self,
|
||||
"À propos de LibreNet Scanner",
|
||||
"<b>LibreNet Scanner 0.1.0</b><br><br>"
|
||||
"Scanner réseau graphique pour Linux, conçu pour Debian 13/KDE.<br>"
|
||||
"Interface : Python + PySide6/Qt6.<br>"
|
||||
"Moteurs externes : arp-scan et Nmap.<br><br>"
|
||||
"Licence du code LibreNet Scanner : GPL-3.0-or-later.",
|
||||
)
|
||||
|
||||
def closeEvent(self, event) -> None:
|
||||
self.stop_scan()
|
||||
super().closeEvent(event)
|
||||
Reference in New Issue
Block a user