-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwatch.py
More file actions
2091 lines (1848 loc) · 91.8 KB
/
netwatch.py
File metadata and controls
2091 lines (1848 loc) · 91.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
NetWatch — browser-controlled AI network monitor
==================================================
Run this file, your browser opens, configure everything in the GUI:
- Anthropic API key
- Targets, interface, thresholds, capture settings, Claude model
- Start/stop monitoring
- Download captured pcap files
Quickstart:
python3 netwatch.py # installs deps automatically on first run
# browser opens at http://127.0.0.1:8765
Optional system dep: tshark (Wireshark) on PATH for packet capture.
On macOS/Linux tcpdump also works. On Windows the pre-built .exe bundles
tshark and the Npcap installer — first launch as Administrator installs
Npcap silently; subsequent launches need no extra setup.
"""
from __future__ import annotations
__version__ = "1.0.2"
import configparser
import json
import logging
import os
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import webbrowser
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
try:
import anthropic
from flask import Flask, abort, jsonify, request, send_file
except ImportError:
import subprocess as _sp, os as _os
print("[netwatch] First run — installing required packages…", flush=True)
_sp.check_call([sys.executable, "-m", "pip", "install", "anthropic", "flask"])
_os.execv(sys.executable, [sys.executable] + sys.argv)
# Mutable container so the heartbeat route and watchdog thread share state.
_heartbeat_time: list[float | None] = [None]
# ═══════════════════════════════════════════════════════════════════════════════
# CONFIG STORE — persists settings + API key to ~/.netwatch.conf
# ═══════════════════════════════════════════════════════════════════════════════
_CONFIG_PATH = Path.home() / ".netwatch.conf"
_DEFAULT_INTERFACE = (
"en0" if sys.platform == "darwin"
else "Ethernet" if sys.platform == "win32"
else "eth0"
)
@dataclass
class Config:
"""All runtime tunables. Loaded from ~/.netwatch.conf, edited via web UI."""
targets: list[str] = field(default_factory=lambda: ["8.8.8.8", "1.1.1.1"])
interface: str = _DEFAULT_INTERFACE # capture interface (tshark/tcpdump)
egress_interface: str = "" # outbound interface for LLM API calls ("" = OS default)
ping_interval: float = 1.0
loss_threshold: int = 20
window_size: int = 10
capture_duration: int = 30
capture_dir: str = "./captures"
cooldown_secs: int = 120
claude_model: str = "claude-opus-4-7"
prebuffer_secs: int = 10
prebuffer_enabled: bool = True
ai_provider: str = "anthropic"
grok_model: str = "grok-3-mini"
ai_enabled: bool = True
def to_dict(self) -> dict:
return {
"targets": self.targets,
"interface": self.interface,
"egress_interface": self.egress_interface,
"ping_interval": self.ping_interval,
"loss_threshold": self.loss_threshold,
"window_size": self.window_size,
"capture_duration": self.capture_duration,
"capture_dir": self.capture_dir,
"cooldown_secs": self.cooldown_secs,
"claude_model": self.claude_model,
"prebuffer_secs": self.prebuffer_secs,
"prebuffer_enabled": self.prebuffer_enabled,
"ai_provider": self.ai_provider,
"grok_model": self.grok_model,
"ai_enabled": self.ai_enabled,
}
def load_config() -> Config:
"""Load config from disk, falling back to defaults for missing fields."""
cfg = Config()
if not _CONFIG_PATH.exists():
return cfg
parser = configparser.ConfigParser()
parser.read(_CONFIG_PATH)
if "config" not in parser:
return cfg
s = parser["config"]
cfg.targets = [t.strip() for t in s.get("targets", "8.8.8.8,1.1.1.1").split(",") if t.strip()]
cfg.interface = s.get("interface", cfg.interface)
cfg.egress_interface = s.get("egress_interface", cfg.egress_interface)
cfg.ping_interval = float(s.get("ping_interval", cfg.ping_interval))
cfg.loss_threshold = int(s.get("loss_threshold", cfg.loss_threshold))
cfg.window_size = int(s.get("window_size", cfg.window_size))
cfg.capture_duration = int(s.get("capture_duration", cfg.capture_duration))
cfg.capture_dir = s.get("capture_dir", cfg.capture_dir)
cfg.cooldown_secs = int(s.get("cooldown_secs", cfg.cooldown_secs))
cfg.claude_model = s.get("claude_model", cfg.claude_model)
cfg.prebuffer_secs = int(s.get("prebuffer_secs", cfg.prebuffer_secs))
cfg.prebuffer_enabled = s.getboolean("prebuffer_enabled", cfg.prebuffer_enabled)
cfg.ai_provider = s.get("ai_provider", cfg.ai_provider)
cfg.grok_model = s.get("grok_model", cfg.grok_model)
cfg.ai_enabled = s.getboolean("ai_enabled", cfg.ai_enabled)
return cfg
def save_config(cfg: Config) -> None:
"""Persist Config to ~/.netwatch.conf (preserving any existing api_key)."""
parser = configparser.ConfigParser()
if _CONFIG_PATH.exists():
parser.read(_CONFIG_PATH)
parser["config"] = {
"targets": ",".join(cfg.targets),
"interface": cfg.interface,
"egress_interface": cfg.egress_interface,
"ping_interval": str(cfg.ping_interval),
"loss_threshold": str(cfg.loss_threshold),
"window_size": str(cfg.window_size),
"capture_duration": str(cfg.capture_duration),
"capture_dir": cfg.capture_dir,
"cooldown_secs": str(cfg.cooldown_secs),
"claude_model": cfg.claude_model,
"prebuffer_secs": str(cfg.prebuffer_secs),
"prebuffer_enabled": str(cfg.prebuffer_enabled),
"ai_provider": cfg.ai_provider,
"grok_model": cfg.grok_model,
"ai_enabled": str(cfg.ai_enabled),
}
with open(_CONFIG_PATH, "w") as f:
parser.write(f)
if sys.platform != "win32":
_CONFIG_PATH.chmod(0o600)
def load_api_key() -> str | None:
"""Read saved Anthropic API key, if any."""
if not _CONFIG_PATH.exists():
return None
parser = configparser.ConfigParser()
parser.read(_CONFIG_PATH)
return parser.get("auth", "api_key", fallback=None) or None
def save_api_key(key: str) -> None:
"""Save Anthropic API key to ~/.netwatch.conf (chmod 600)."""
parser = configparser.ConfigParser()
if _CONFIG_PATH.exists():
parser.read(_CONFIG_PATH)
parser["auth"] = {"api_key": key}
with open(_CONFIG_PATH, "w") as f:
parser.write(f)
if sys.platform != "win32":
_CONFIG_PATH.chmod(0o600)
def load_grok_api_key() -> str | None:
"""Read saved xAI Grok API key, if any."""
if not _CONFIG_PATH.exists():
return None
parser = configparser.ConfigParser()
parser.read(_CONFIG_PATH)
return parser.get("grok", "api_key", fallback=None) or None
def save_grok_api_key(key: str) -> None:
"""Save xAI Grok API key to ~/.netwatch.conf (chmod 600)."""
parser = configparser.ConfigParser()
if _CONFIG_PATH.exists():
parser.read(_CONFIG_PATH)
parser["grok"] = {"api_key": key}
with open(_CONFIG_PATH, "w") as f:
parser.write(f)
if sys.platform != "win32":
_CONFIG_PATH.chmod(0o600)
def get_interface_ip(iface: str) -> str | None:
"""Return the first IPv4 address bound to *iface*, or None on failure."""
if not iface:
return None
import re as _re
if sys.platform == "win32":
# `netsh interface ip show address` gives per-interface IP info
try:
out = subprocess.check_output(
["netsh", "interface", "ip", "show", "address", iface],
text=True, stderr=subprocess.DEVNULL,
)
m = _re.search(r"IP Address[:\s]+(\d+\.\d+\.\d+\.\d+)", out)
if m:
return m.group(1)
except Exception:
pass
elif sys.platform == "darwin":
try:
out = subprocess.check_output(
["ipconfig", "getifaddr", iface], text=True, stderr=subprocess.DEVNULL
).strip()
if out:
return out
except Exception:
pass
else:
try:
out = subprocess.check_output(
["ip", "-4", "addr", "show", iface], text=True, stderr=subprocess.DEVNULL
)
m = _re.search(r"inet (\d+\.\d+\.\d+\.\d+)", out)
if m:
return m.group(1)
except Exception:
pass
return None
# ═══════════════════════════════════════════════════════════════════════════════
# MONITOR — ping + rolling loss windows
# ═══════════════════════════════════════════════════════════════════════════════
class PingWindow:
"""Thread-safe rolling window of ping results."""
def __init__(self, maxlen: int = 10) -> None:
self._dq: deque[bool] = deque(maxlen=maxlen)
self._lock = threading.Lock()
def record(self, success: bool) -> None:
with self._lock:
self._dq.append(success)
def loss_pct(self) -> float:
with self._lock:
if not self._dq:
return 0.0
return sum(1 for r in self._dq if not r) / len(self._dq) * 100.0
def snapshot(self) -> list[bool]:
with self._lock:
return list(self._dq)
class PingMonitor:
"""Manages PingWindows for all configured targets."""
def __init__(self, targets: list[str], window_size: int = 10) -> None:
self.targets = targets
self.windows = {t: PingWindow(window_size) for t in targets}
def ping(self, host: str, timeout_ms: int = 1000) -> bool:
if sys.platform == "win32":
cmd = ["ping", "-n", "1", "-w", str(timeout_ms), host]
elif sys.platform == "darwin":
cmd = ["ping", "-c", "1", "-W", str(timeout_ms), host]
else:
cmd = ["ping", "-c", "1", "-w", str(max(1, timeout_ms // 1000)), host]
try:
r = subprocess.run(cmd, capture_output=True, timeout=timeout_ms / 1000 + 2)
return r.returncode == 0
except (subprocess.TimeoutExpired, OSError):
return False
def record(self, host: str, success: bool) -> None:
self.windows[host].record(success)
def loss_pct(self, host: str) -> float:
return self.windows[host].loss_pct()
def snapshot_all(self) -> dict[str, float]:
return {t: self.windows[t].loss_pct() for t in self.targets}
# ═══════════════════════════════════════════════════════════════════════════════
# CAPTURE — tshark/tcpdump + always-on ring buffer
# ═══════════════════════════════════════════════════════════════════════════════
def _bundled_resource_dir() -> Path:
"""Directory containing bundled resources (tshark, npcap installer).
When frozen by PyInstaller --onefile, resources are extracted to sys._MEIPASS.
When running from source, resources live next to this script.
"""
base = getattr(sys, "_MEIPASS", None)
return Path(base) if base else Path(__file__).resolve().parent
def _bundled_wireshark_dir() -> Path | None:
d = _bundled_resource_dir() / "tools" / "wireshark"
return d if (d / ("tshark.exe" if sys.platform == "win32" else "tshark")).exists() else None
def _is_admin_windows() -> bool:
if sys.platform != "win32":
return True
try:
import ctypes
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def _npcap_installed() -> bool:
"""Detect Npcap on Windows. Checks the service first, then wpcap.dll."""
if sys.platform != "win32":
return True
try:
r = subprocess.run(["sc", "query", "npcap"], capture_output=True, timeout=5)
if r.returncode == 0 and b"STATE" in r.stdout:
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
sysroot = Path(os.environ.get("SystemRoot", r"C:\Windows"))
for candidate in (sysroot / "System32" / "Npcap" / "wpcap.dll",
sysroot / "System32" / "wpcap.dll"):
if candidate.exists():
return True
return False
def _run_with_heartbeat(cmd: list[str], label: str, timeout: int) -> int:
"""Run a child process while printing a dot every 2 s so the console doesn't look frozen."""
print(f" [*] {label} ", end="", flush=True)
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
waited = 0
try:
while True:
try:
rc = proc.wait(timeout=2)
print(" done.", flush=True)
return rc
except subprocess.TimeoutExpired:
print(".", end="", flush=True)
waited += 2
if waited >= timeout:
proc.kill()
print(" timed out.", flush=True)
return -1
except KeyboardInterrupt:
proc.kill()
raise
def ensure_npcap_windows() -> None:
"""Install bundled Npcap if missing. No-op on non-Windows or when already installed."""
if sys.platform != "win32":
return
if _npcap_installed():
print(" [ok] Npcap driver already installed.", flush=True)
return
installer = _bundled_resource_dir() / "tools" / "npcap-installer.exe"
if not installer.exists():
print(" [!!] Npcap is not installed and no bundled installer was found.", flush=True)
print(" Install Npcap from https://npcap.com/ to enable packet capture.", flush=True)
return
print(" [..] Npcap not detected — running first-time installer (silent).", flush=True)
if not _is_admin_windows():
print(" This needs Administrator rights — Windows will show a UAC prompt.", flush=True)
args = ["/S", "/winpcap_mode=yes", "/admin_only=no",
"/loopback_support=yes", "/dlt_null=yes"]
if _is_admin_windows():
rc = _run_with_heartbeat([str(installer)] + args,
"Installing Npcap (no admin prompt, already elevated)",
timeout=300)
else:
ps = (
f"Start-Process -FilePath '{installer}' "
f"-ArgumentList '{' '.join(args)}' -Verb RunAs -Wait"
)
rc = _run_with_heartbeat(
["powershell", "-NoProfile", "-Command", ps],
"Waiting for Npcap installer (approve the UAC prompt)",
timeout=600,
)
if rc == 0 and _npcap_installed():
print(" [ok] Npcap installed successfully.", flush=True)
else:
print(" [!!] Npcap install did not complete — capture will not work until it is installed.",
flush=True)
def detect_capture_tool() -> str:
# 1. Bundled tshark (shipped inside the PyInstaller exe). Highest priority so
# a user with a partial/old Wireshark install still gets the version we tested with.
bundled = _bundled_wireshark_dir()
if bundled is not None:
os.environ["PATH"] = str(bundled) + os.pathsep + os.environ.get("PATH", "")
# 2. On Windows, also probe common Wireshark install locations as a fallback.
if sys.platform == "win32":
_wireshark_dirs = [
Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Wireshark",
Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Wireshark",
]
for d in _wireshark_dirs:
if (d / "tshark.exe").exists():
os.environ["PATH"] = os.environ.get("PATH", "") + os.pathsep + str(d)
break
tools = ["tshark"] if sys.platform == "win32" else ["tshark", "tcpdump"]
for tool in tools:
try:
subprocess.run([tool, "--version"], capture_output=True, timeout=5)
return tool
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
if sys.platform == "win32":
raise RuntimeError(
"tshark not found. The pre-built netwatch.exe ships tshark internally — "
"if you're running from source, install Wireshark from wireshark.org."
)
raise RuntimeError("Neither tshark nor tcpdump found. Install wireshark or tcpdump.")
def run_capture(interface: str, duration: int, pcap_path: str, tool: str, host_filter: str = "") -> None:
if tool == "tshark":
cmd = ["tshark", "-i", interface, "-a", f"duration:{duration}", "-w", pcap_path]
if host_filter:
cmd += ["-f", f"host {host_filter}"]
else:
cmd = ["tcpdump", "-i", interface, "-G", str(duration), "-W", "1", "-w", pcap_path]
if host_filter:
cmd += [f"host {host_filter}"]
try:
r = subprocess.run(cmd, capture_output=True, timeout=duration + 15)
except PermissionError as exc:
if sys.platform == "win32":
raise PermissionError(f"{tool} needs Administrator privileges.") from exc
raise PermissionError(f"{tool} needs elevated privileges. Try: sudo python3 netwatch.py") from exc
stderr = r.stderr.decode(errors="replace").strip()
pcap = Path(pcap_path)
wrote_file = pcap.exists() and pcap.stat().st_size > 0
# tshark sometimes exits 1 on normal completion; tcpdump exit 1 is a real error.
# Either way, the source of truth is whether a non-empty pcap file was written.
if not wrote_file:
msg = stderr or f"(no stderr; exit {r.returncode})"
lower = stderr.lower()
if "permission" in lower or "operation not permitted" in lower or "you don't have" in lower:
hint = (
"Run with `sudo python3 netwatch.py` (macOS/Linux), or install Wireshark "
"and run its ChmodBPF helper to grant your user BPF access."
if sys.platform != "win32"
else "Run this script as Administrator."
)
raise PermissionError(f"{tool} cannot capture on {interface} — {msg}. {hint}")
raise RuntimeError(f"{tool} produced no pcap (exit {r.returncode}): {msg}")
def get_capture_summary(pcap_path: str) -> str:
if not Path(pcap_path).exists():
return "(pcap file not found)"
try:
r = subprocess.run(
["tshark", "-r", pcap_path, "-z", "io,stat,0", "-q"],
capture_output=True, timeout=30,
)
lines = r.stdout.decode(errors="replace").strip().splitlines()
if len(lines) > 50:
lines = lines[:50] + [f"... ({len(lines) - 50} lines truncated)"]
return "\n".join(lines) or "(no output from tshark)"
except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
return f"(summary unavailable: {exc})"
def _merge_pcaps(inputs: list[str], output: str) -> None:
existing = [f for f in inputs if Path(f).exists()]
if not existing:
return
try:
subprocess.run(["mergecap", "-w", output] + existing, capture_output=True, timeout=30)
except FileNotFoundError:
print("[netwatch] mergecap not found — prebuffer will not be prepended to capture. Install Wireshark to enable this.", flush=True)
except subprocess.TimeoutExpired:
pass
class RingBufferCapture:
"""Always-on tshark ring buffer keeping the last N seconds of traffic."""
def __init__(self, interface: str, capture_dir: str, prebuffer_secs: int = 10, tag: str = "pre") -> None:
self.interface = interface
self.capture_dir = capture_dir
self.prebuffer_secs = prebuffer_secs
self.tag = tag
self._proc: subprocess.Popen | None = None
self._thread: threading.Thread | None = None
self._stop_event = threading.Event()
@property
def ring_pattern(self) -> str:
return str(Path(self.capture_dir) / f"{self.tag}_ring.pcap")
def start(self) -> None:
self._stop_event.clear()
self._thread = threading.Thread(target=self._run, daemon=True, name="ring-capture")
self._thread.start()
def _run(self) -> None:
cmd = [
"tshark", "-i", self.interface,
"-b", f"duration:{self.prebuffer_secs}",
"-b", "files:3",
"-w", self.ring_pattern,
]
try:
self._proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self._stop_event.wait()
self._proc.terminate()
try:
self._proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self._proc.kill()
except (FileNotFoundError, PermissionError):
pass
def freeze(self) -> list[str]:
self._stop_event.set()
if self._thread:
self._thread.join(timeout=8)
return sorted(str(p) for p in Path(self.capture_dir).glob(f"{self.tag}_ring*.pcap"))
def stop(self) -> None:
self._stop_event.set()
if self._thread:
self._thread.join(timeout=8)
for f in Path(self.capture_dir).glob(f"{self.tag}_ring*.pcap"):
try:
f.unlink()
except OSError:
pass
class CaptureManager:
"""Optional ring-buffer pre-capture + on-demand outage capture."""
def __init__(self, interface: str, capture_dir: str, capture_duration: int,
prebuffer_enabled: bool = True, prebuffer_secs: int = 10) -> None:
self.interface = interface
self.capture_dir = capture_dir
self.capture_duration = capture_duration
self.tool = detect_capture_tool()
self._ring: RingBufferCapture | None = None
self._prebuffer_secs = prebuffer_secs
self._ring_lock = threading.Lock()
if prebuffer_enabled and self.tool == "tshark":
self._ring = RingBufferCapture(interface, capture_dir, prebuffer_secs)
def start_prebuffer(self) -> None:
if self._ring:
self._ring.start()
def trigger(self, label: str, host_filter: str = "") -> tuple[str, str]:
ts = time.strftime("%Y%m%d_%H%M%S")
pcap_path = str(Path(self.capture_dir) / f"capture_{label}_{ts}.pcap")
pre_files: list[str] = []
with self._ring_lock:
if self._ring:
pre_files = self._ring.freeze()
self._ring = RingBufferCapture(self.interface, self.capture_dir, self._prebuffer_secs)
self._ring.start()
run_capture(self.interface, self.capture_duration, pcap_path, self.tool, host_filter)
if pre_files and self.tool == "tshark":
merged = pcap_path.replace(".pcap", "_merged.pcap")
_merge_pcaps(pre_files + [pcap_path], merged)
if Path(merged).exists():
Path(pcap_path).unlink(missing_ok=True)
Path(merged).rename(pcap_path)
for f in pre_files:
Path(f).unlink(missing_ok=True)
return pcap_path, get_capture_summary(pcap_path)
def stop(self) -> None:
if self._ring:
self._ring.stop()
# ═══════════════════════════════════════════════════════════════════════════════
# ANALYZER — Claude API
# ═══════════════════════════════════════════════════════════════════════════════
class ClaudeAnalyzer:
"""Sends a structured prompt to Claude for root-cause analysis."""
def __init__(self, config: Config) -> None:
self.config = config
def _make_anthropic_client(self) -> "anthropic.Anthropic":
import httpx
ip = get_interface_ip(self.config.egress_interface)
if ip:
transport = httpx.HTTPTransport(local_address=ip)
http_client = httpx.Client(transport=transport)
return anthropic.Anthropic(http_client=http_client)
return anthropic.Anthropic()
def analyze(self, targets: list[str], loss: dict[str, float], summary: str, pcap_path: str) -> str:
prompt = self._build_prompt(targets, loss, summary, pcap_path)
if self.config.ai_provider == "grok":
return self._invoke_grok(prompt)
try:
return self._invoke_anthropic(prompt)
except anthropic.RateLimitError:
time.sleep(60)
return self._invoke_anthropic(prompt)
def _build_prompt(self, targets: list[str], loss: dict[str, float], summary: str, pcap_path: str) -> str:
loss_lines = "\n".join(f"- {h}: {l:.1f}% packet loss" for h, l in loss.items())
return f"""You are an expert network engineer and packet analysis specialist.
Analyze the following packet capture summary from a network target that went offline and triggered an automatic packet capture. The capture was started by the monitoring app after the target was offline for a configured period of time.
**Affected Target(s):** {", ".join(targets)}
**Packet Loss at Trigger:** {loss_lines}
**Capture File:** `{pcap_path}` (filtered to traffic involving the affected target)
**Packet Capture Summary:**
```
{summary}
```
**Core Principles:**
- Always troubleshoot systematically using the OSI model (Layer 1 → Layer 7).
- Be conservative, evidence-based, and realistic. Simple physical link flaps, cable disconnects, or interface issues are the most common causes of brief outages.
- Do not hallucinate or over-diagnose storms, loops, or attacks unless the data clearly supports it.
- Normal reconnection behavior (extra ARP, DHCP renewals, TCP retransmissions, duplicate frames during recovery) is expected and usually benign.
**OSI-Based Analysis Order:**
- Layer 1 (Physical): Link up/down events, interface flaps, cable issues
- Layer 2 (Data Link): ARP behavior, MAC flapping, broadcast/multicast storms, switching loops
- Layer 3 (Network): IP routing, ICMP, DHCP requests/renewals
- Layer 4+ (Transport & above): TCP/UDP retransmissions, session recovery, resets
**Structure your response exactly like this:**
**1. Capture Overview**
- Duration of capture:
- Total packets:
- Approximate outage window (based on traffic patterns):
- Top 5 protocols by volume:
- Top 5 talkers (src/dest) by packet count:
**2. OSI Layer Analysis**
- Layer 1 (Physical):
- Layer 2 (Data Link):
- Layer 3 (Network):
- Layer 4+ (Transport & higher):
**3. Key Findings**
List only real issues with clear evidence (timestamps, packet counts, MAC/IP). Use severity: Critical / High / Medium / Low / Normal Behavior
**4. Root Cause Conclusion**
Most likely explanation (be realistic — "simple link flap / cable disconnect" is a valid and common answer).
**5. Recommendations**
- Immediate actions
- Long-term prevention (if needed)
Be professional, concise, and non-alarmist. Prefer the simplest explanation that fits the evidence.
"""
def _invoke_anthropic(self, prompt: str) -> str:
client = self._make_anthropic_client()
response = client.messages.create(
model=self.config.claude_model,
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
return response.content[0].text
def _invoke_grok(self, prompt: str) -> str:
import httpx
key = os.environ.get("GROK_API_KEY", "")
if not key:
raise RuntimeError("Grok API key not set — add it in Settings")
payload = {
"model": self.config.grok_model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 1024,
}
ip = get_interface_ip(self.config.egress_interface)
transport = httpx.HTTPTransport(local_address=ip) if ip else None
with httpx.Client(transport=transport, timeout=120) as client:
resp = client.post(
"https://api.x.ai/v1/chat/completions",
json=payload,
headers={"Authorization": f"Bearer {key}"},
)
if resp.status_code != 200:
raise RuntimeError(f"Grok API error {resp.status_code}: {resp.text}")
return resp.json()["choices"][0]["message"]["content"]
# ═══════════════════════════════════════════════════════════════════════════════
# WEB STATE — thread-safe state shared between NetWatch and the HTTP API
# ═══════════════════════════════════════════════════════════════════════════════
@dataclass
class WebState:
"""Live state consumed by /api/status."""
targets: list[str]
interface: str
capture_duration: int
cooldown_secs: int
tool: str = ""
window_snaps: dict[str, list[bool]] = field(default_factory=dict)
loss_pct: dict[str, float] = field(default_factory=dict)
events: deque = field(default_factory=lambda: deque(maxlen=200))
analyses: deque = field(default_factory=lambda: deque(maxlen=20))
capturing: dict[str, float] = field(default_factory=dict)
analyzing: set = field(default_factory=set)
last_cap_time: dict[str, float] = field(default_factory=dict)
start_time: float = field(default_factory=time.time)
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False)
def __post_init__(self) -> None:
for t in self.targets:
self.window_snaps.setdefault(t, [])
self.loss_pct.setdefault(t, 0.0)
def add_event(self, level: str, msg: str) -> None:
ts = datetime.now().strftime("%H:%M:%S")
with self._lock:
self.events.appendleft((ts, level.upper(), msg))
def update_target(self, host: str, snap: list[bool], loss: float) -> None:
with self._lock:
self.window_snaps[host] = snap
self.loss_pct[host] = loss
def set_analysis(self, text: str, target: str = "") -> None:
ts = datetime.now().strftime("%H:%M:%S")
entry = {"id": f"{target}-{ts}", "target": target, "time": ts, "text": text}
with self._lock:
self.analyses.appendleft(entry)
def clear(self) -> None:
"""Reset ping history, analyses, and event log without stopping the monitor."""
with self._lock:
for t in self.targets:
self.window_snaps[t] = []
self.loss_pct[t] = 0.0
self.events.clear()
self.analyses.clear()
def set_capturing(self, target: str, active: bool) -> None:
with self._lock:
now = time.time()
if active:
self.capturing[target] = now
self.last_cap_time[target] = now
else:
self.capturing.pop(target, None)
def set_analyzing(self, target: str, active: bool) -> None:
with self._lock:
if active:
self.analyzing.add(target)
else:
self.analyzing.discard(target)
def snapshot(self) -> dict:
with self._lock:
uptime_s = int(time.time() - self.start_time)
h, rem = divmod(uptime_s, 3600)
m, s = divmod(rem, 60)
now = time.time()
capturing_targets = [
{
"target": t,
"elapsed": now - started,
"duration": self.capture_duration,
}
for t, started in self.capturing.items()
]
cooldowns = [
max(0.0, self.cooldown_secs - (now - lct))
for lct in self.last_cap_time.values()
]
cooldown_remaining = max(cooldowns) if cooldowns else 0
return {
"targets": list(self.targets),
"interface": self.interface,
"tool": self.tool,
"uptime": f"{h:02d}:{m:02d}:{s:02d}",
"window_snaps": dict(self.window_snaps),
"loss_pct": dict(self.loss_pct),
"events": list(self.events),
"analyses": list(self.analyses),
"capturing_targets": capturing_targets,
"analyzing_targets": list(self.analyzing),
"capture_duration": self.capture_duration,
"cooldown_remaining": cooldown_remaining,
}
# ═══════════════════════════════════════════════════════════════════════════════
# ORCHESTRATOR
# ═══════════════════════════════════════════════════════════════════════════════
class NetWatch:
"""Wires together monitor + capture + analyzer; updates a WebState."""
def __init__(self, config: Config, state: WebState) -> None:
self.config = config
self.state = state
self.monitor = PingMonitor(config.targets, config.window_size)
self.capture = CaptureManager(
config.interface, config.capture_dir, config.capture_duration,
config.prebuffer_enabled, config.prebuffer_secs,
)
state.tool = self.capture.tool
self.analyzer = ClaudeAnalyzer(config)
self._running = False
self._capturing_lock = threading.Lock()
self._capturing: set[str] = set()
self._last_cap: dict[str, float] = {}
def run(self) -> None:
self._running = True
os.makedirs(self.config.capture_dir, exist_ok=True)
try:
self.capture.start_prebuffer()
except Exception as exc:
self.state.add_event("WARN", f"Pre-buffer disabled: {exc}")
self.state.add_event("INFO", f"Monitoring: {', '.join(self.config.targets)}")
self.state.add_event("INFO", f"Interface: {self.config.interface} • Threshold: {self.config.loss_threshold}%")
while self._running:
for target in self.config.targets:
if not self._running:
break
success = self.monitor.ping(target)
self.monitor.record(target, success)
snap = self.monitor.windows[target].snapshot()
loss = self.monitor.loss_pct(target)
self.state.update_target(target, snap, loss)
if loss >= self.config.loss_threshold:
self._maybe_trigger(target, loss)
time.sleep(self.config.ping_interval)
def _maybe_trigger(self, target: str, loss: float) -> None:
now = time.time()
with self._capturing_lock:
if target in self._capturing:
return
if (now - self._last_cap.get(target, 0.0)) < self.config.cooldown_secs:
return
self._capturing.add(target)
self._last_cap[target] = now
self.state.set_capturing(target, True)
threading.Thread(target=self._capture_and_analyze, args=(target, loss), daemon=True).start()
def _capture_and_analyze(self, target: str, loss: float) -> None:
self.state.add_event("CAPTURE", f"{target} at {loss:.1f}% loss — {self.config.capture_duration}s capture started")
try:
label = target.replace(".", "_").replace(":", "_")
pcap_path, summary = self.capture.trigger(label=label, host_filter=target)
# Pcap is written — clear the progress bar before the (potentially slow) API call
self.state.set_capturing(target, False)
self.state.add_event("CAPTURE", f"Saved: {Path(pcap_path).name}")
if self.config.ai_enabled:
_ai_label = "Grok" if self.config.ai_provider == "grok" else "Claude"
self.state.add_event("ANALYSIS", f"Sending {target} capture to {_ai_label}…")
self.state.set_analyzing(target, True)
try:
analysis = self.analyzer.analyze([target], {target: loss}, summary, pcap_path)
finally:
self.state.set_analyzing(target, False)
self.state.set_analysis(analysis, target=target)
self.state.add_event("ANALYSIS", f"Analysis complete for {target}")
except Exception as exc:
self.state.add_event("ERROR", f"Capture/analysis failed for {target}: {exc}")
finally:
with self._capturing_lock:
self._capturing.discard(target)
self.state.set_capturing(target, False)
def stop(self) -> None:
self._running = False
self.capture.stop()
with self._capturing_lock:
for target in list(self._capturing):
self.state.set_capturing(target, False)
self.state.add_event("INFO", "Monitoring stopped")
# ═══════════════════════════════════════════════════════════════════════════════
# CONTROLLER — singleton holding the active NetWatch + thread + state
# ═══════════════════════════════════════════════════════════════════════════════
class Controller:
"""Holds current config and the (optional) running NetWatch instance."""
def __init__(self) -> None:
self.config = load_config()
save_config(self.config) # ensure [config] section is always written on startup
self.state: WebState | None = None
self._netwatch: NetWatch | None = None
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
saved = load_api_key()
if saved:
os.environ["ANTHROPIC_API_KEY"] = saved
saved_grok = load_grok_api_key()
if saved_grok:
os.environ["GROK_API_KEY"] = saved_grok
@property
def running(self) -> bool:
return self._thread is not None and self._thread.is_alive()
def start(self) -> tuple[bool, str]:
with self._lock:
if self.running:
return False, "Already running"
if self.config.ai_enabled:
if self.config.ai_provider == "grok" and not os.environ.get("GROK_API_KEY"):
return False, "Set your xAI Grok API key first (Settings → API Key)"
if self.config.ai_provider != "grok" and not os.environ.get("ANTHROPIC_API_KEY"):
return False, "Set your Anthropic API key first (Settings → API Key)"
try:
self.state = WebState(
targets=list(self.config.targets),
interface=self.config.interface,
capture_duration=self.config.capture_duration,
cooldown_secs=self.config.cooldown_secs,
)
self._netwatch = NetWatch(self.config, self.state)
except Exception as exc:
return False, f"Failed to initialise: {exc}"
self._thread = threading.Thread(target=self._netwatch.run, daemon=True, name="netwatch")
self._thread.start()
return True, "Started"
def stop(self) -> tuple[bool, str]:
with self._lock:
if not self.running or self._netwatch is None:
return False, "Not running"
self._netwatch.stop()
if self._thread:
self._thread.join(timeout=5)
self._thread = None
return True, "Stopped"
def update_config(self, data: dict) -> tuple[bool, str]:
try:
new = Config(**data)
except TypeError as exc:
return False, f"Bad config: {exc}"
save_config(new)
with self._lock:
self.config = new
return True, "Saved (restart monitoring to apply)"
def get_state(self) -> dict:
base = {
"running": self.running,
"interface": self.config.interface,
"targets": list(self.config.targets),
"tool": "",
"uptime": "00:00:00",
"window_snaps": {t: [] for t in self.config.targets},
"loss_pct": {t: 0.0 for t in self.config.targets},
"events": [],
"analyses": [],