sysmaint 0.1.0__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.
Files changed (57) hide show
  1. sysmaint/__init__.py +17 -0
  2. sysmaint/__main__.py +6 -0
  3. sysmaint/cli.py +637 -0
  4. sysmaint/config.py +229 -0
  5. sysmaint/gui/__init__.py +5 -0
  6. sysmaint/gui/app.py +193 -0
  7. sysmaint/gui/components/__init__.py +13 -0
  8. sysmaint/gui/components/cards.py +239 -0
  9. sysmaint/gui/components/console.py +61 -0
  10. sysmaint/gui/components/dialogs.py +79 -0
  11. sysmaint/gui/theme.py +52 -0
  12. sysmaint/gui/views/__init__.py +25 -0
  13. sysmaint/gui/views/backup.py +167 -0
  14. sysmaint/gui/views/cleaner.py +227 -0
  15. sysmaint/gui/views/dashboard.py +252 -0
  16. sysmaint/gui/views/diagnostics.py +243 -0
  17. sysmaint/gui/views/integrity.py +158 -0
  18. sysmaint/gui/views/malware.py +293 -0
  19. sysmaint/gui/views/network.py +171 -0
  20. sysmaint/gui/views/security.py +118 -0
  21. sysmaint/gui/views/settings.py +211 -0
  22. sysmaint/gui/views/startup.py +133 -0
  23. sysmaint/logging_setup.py +62 -0
  24. sysmaint/modules/__init__.py +41 -0
  25. sysmaint/modules/backup.py +106 -0
  26. sysmaint/modules/cleaner.py +249 -0
  27. sysmaint/modules/disk.py +160 -0
  28. sysmaint/modules/drivers.py +89 -0
  29. sysmaint/modules/integrity.py +148 -0
  30. sysmaint/modules/malware.py +412 -0
  31. sysmaint/modules/memory.py +105 -0
  32. sysmaint/modules/network.py +167 -0
  33. sysmaint/modules/optimizer.py +186 -0
  34. sysmaint/modules/recovery.py +353 -0
  35. sysmaint/modules/report.py +232 -0
  36. sysmaint/modules/restore.py +123 -0
  37. sysmaint/modules/scheduler.py +137 -0
  38. sysmaint/modules/security.py +88 -0
  39. sysmaint/modules/services.py +171 -0
  40. sysmaint/modules/startup.py +95 -0
  41. sysmaint/modules/sysinfo.py +112 -0
  42. sysmaint/service/__init__.py +5 -0
  43. sysmaint/service/server.py +210 -0
  44. sysmaint/tui/__init__.py +5 -0
  45. sysmaint/tui/app.py +830 -0
  46. sysmaint/tui/modals.py +201 -0
  47. sysmaint/tui/themes.py +97 -0
  48. sysmaint/utils/__init__.py +39 -0
  49. sysmaint/utils/common.py +255 -0
  50. sysmaint/utils/escalate.py +93 -0
  51. sysmaint/utils/linux.py +240 -0
  52. sysmaint/utils/parsers.py +171 -0
  53. sysmaint/utils/windows.py +308 -0
  54. sysmaint-0.1.0.dist-info/METADATA +307 -0
  55. sysmaint-0.1.0.dist-info/RECORD +57 -0
  56. sysmaint-0.1.0.dist-info/WHEEL +4 -0
  57. sysmaint-0.1.0.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,412 @@
1
+ # sysmaint/modules/malware.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import os
8
+ import platform
9
+ import shutil
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import requests
15
+
16
+ from ..config import MalwareConfig
17
+ from ..utils.common import compute_sha256, run_command
18
+ from ..utils.parsers import parse_clamscan_output
19
+
20
+ logger = logging.getLogger("sysmaint.malware")
21
+
22
+ BUILTIN_HEURISTIC_YARA_RULES = """
23
+ rule Suspicious_Powershell_Bypass {
24
+ meta:
25
+ description = "Detects hidden execution and bypass executionpolicy"
26
+ author = "SysMaint Toolkit"
27
+ severity = "High"
28
+ strings:
29
+ $p1 = "-ExecutionPolicy Bypass" nocase
30
+ $p2 = "-NoProfile -NonInteractive -WindowStyle Hidden" nocase
31
+ $p3 = "DownloadString(" nocase
32
+ $p4 = "IEX(" nocase
33
+ $p5 = "Invoke-Expression" nocase
34
+ condition:
35
+ ($p1 and $p2) or ($p3 and $p5) or ($p3 and $p4)
36
+ }
37
+
38
+ rule WebShell_Generic_PHP {
39
+ meta:
40
+ description = "Detects generic PHP webshell patterns"
41
+ author = "SysMaint Toolkit"
42
+ severity = "High"
43
+ strings:
44
+ $eval = "eval(base64_decode(" nocase
45
+ $shell = "passthru($_" nocase
46
+ $exec = "shell_exec($_" nocase
47
+ $system = "system($_GET" nocase
48
+ condition:
49
+ any of them
50
+ }
51
+
52
+ rule Suspicious_Script_Drop {
53
+ meta:
54
+ description = "Detects dangerous script drop or obfuscation"
55
+ author = "SysMaint Toolkit"
56
+ severity = "Medium"
57
+ strings:
58
+ $wscript = "WScript.Shell" nocase
59
+ $cscript = "cscript.exe" nocase
60
+ $certutil = "certutil -urlcache -split -f" nocase
61
+ $bitsadmin = "bitsadmin /transfer" nocase
62
+ condition:
63
+ $certutil or $bitsadmin or ($wscript and $cscript)
64
+ }
65
+ """
66
+
67
+
68
+ def get_default_scan_paths() -> list[Path]:
69
+ """
70
+ Return high-priority quick scan paths (Temp, Downloads, Startup).
71
+ """
72
+ paths: list[Path] = []
73
+ user_home = Path.home()
74
+
75
+ # Downloads
76
+ downloads = user_home / "Downloads"
77
+ if downloads.is_dir():
78
+ paths.append(downloads)
79
+
80
+ # Temp directories
81
+ temp_env = os.environ.get("TEMP") or os.environ.get("TMP")
82
+ if temp_env and Path(temp_env).is_dir():
83
+ paths.append(Path(temp_env))
84
+
85
+ if platform.system().lower() == "windows":
86
+ appdata = os.environ.get("APPDATA")
87
+ if appdata:
88
+ startup = Path(appdata) / r"Microsoft\Windows\Start Menu\Programs\Startup"
89
+ if startup.is_dir():
90
+ paths.append(startup)
91
+ local_app_data = os.environ.get("LOCALAPPDATA")
92
+ if local_app_data:
93
+ temp_local = Path(local_app_data) / "Temp"
94
+ if temp_local.is_dir() and temp_local not in paths:
95
+ paths.append(temp_local)
96
+ else:
97
+ linux_temp = Path("/tmp")
98
+ if linux_temp.is_dir():
99
+ paths.append(linux_temp)
100
+ autostart = user_home / ".config" / "autostart"
101
+ if autostart.is_dir():
102
+ paths.append(autostart)
103
+
104
+ return paths
105
+
106
+
107
+ def update_malware_database() -> dict[str, Any]:
108
+ """
109
+ Update ClamAV signature database using freshclam.
110
+ """
111
+ if not shutil.which("freshclam"):
112
+ return {"updated": False, "error": "freshclam executable not found in PATH"}
113
+ logger.info("Updating ClamAV signature database via freshclam")
114
+ result = run_command(["freshclam"], check=False)
115
+ return {
116
+ "updated": result.returncode == 0,
117
+ "returncode": result.returncode,
118
+ "output": result.stdout,
119
+ "stderr": result.stderr,
120
+ }
121
+
122
+
123
+ def query_virustotal_hash(file_hash: str, api_key: str) -> dict[str, Any]:
124
+ """
125
+ Query VirusTotal v3 API for a file's SHA-256 hash reputation.
126
+ """
127
+ if not api_key:
128
+ return {"error": "VirusTotal API key is missing"}
129
+
130
+ url = f"https://www.virustotal.com/api/v3/files/{file_hash}"
131
+ headers = {"x-apikey": api_key, "User-Agent": "SysMaint-Toolkit/2.0"}
132
+
133
+ try:
134
+ response = requests.get(url, headers=headers, timeout=15)
135
+ if response.status_code == 200:
136
+ data = response.json().get("data", {})
137
+ attributes = data.get("attributes", {})
138
+ stats = attributes.get("last_analysis_stats", {})
139
+ malicious = stats.get("malicious", 0)
140
+ suspicious = stats.get("suspicious", 0)
141
+ undetected = stats.get("undetected", 0)
142
+ harmless = stats.get("harmless", 0)
143
+
144
+ return {
145
+ "found": True,
146
+ "sha256": file_hash,
147
+ "malicious_count": malicious,
148
+ "suspicious_count": suspicious,
149
+ "harmless_count": harmless,
150
+ "undetected_count": undetected,
151
+ "reputation": attributes.get("reputation", 0),
152
+ "meaningful_name": attributes.get("meaningful_name") or attributes.get("type_description"),
153
+ "is_threat": (malicious + suspicious) > 2,
154
+ }
155
+ elif response.status_code == 404:
156
+ return {"found": False, "sha256": file_hash, "message": "File hash not found in VirusTotal database."}
157
+ else:
158
+ return {"error": f"VirusTotal API HTTP error {response.status_code}: {response.text[:200]}"}
159
+ except Exception as exc:
160
+ return {"error": f"Failed to query VirusTotal: {exc}"}
161
+
162
+
163
+ def scan(
164
+ config: MalwareConfig,
165
+ target: str | Path | None = None,
166
+ offline: bool = False,
167
+ quick_scan: bool = True,
168
+ ) -> dict[str, Any]:
169
+ """
170
+ Perform multi-engine malware scanning (ClamAV, YARA rules, VirusTotal reputation).
171
+
172
+ Args:
173
+ config: MalwareConfig configuration.
174
+ target: Optional specific file or folder to scan.
175
+ offline: If True, skip online threat intelligence lookups.
176
+ quick_scan: If True and target is not specified, scan high-risk locations.
177
+
178
+ Returns:
179
+ Dictionary containing detected threats, scanned metrics, and engine statuses.
180
+ """
181
+ threats: list[dict[str, Any]] = []
182
+ engine_results: dict[str, Any] = {"clamav": None, "yara": None, "virustotal": None}
183
+ scanned_files_count = 0
184
+
185
+ scan_targets: list[Path] = []
186
+ if target:
187
+ scan_targets = [Path(target)]
188
+ elif quick_scan:
189
+ scan_targets = get_default_scan_paths()
190
+ else:
191
+ scan_targets = [Path("C:\\") if platform.system().lower() == "windows" else Path("/")]
192
+
193
+ # 1. ClamAV Scan
194
+ if config.use_clamav:
195
+ if shutil.which("clamscan"):
196
+ clam_threats = []
197
+ for t_path in scan_targets:
198
+ if not t_path.exists():
199
+ continue
200
+ cmd = ["clamscan", "-r", "--no-summary", str(t_path)]
201
+ logger.info("Running ClamAV scan on %s", t_path)
202
+ clam_res = run_command(cmd, check=False)
203
+ parsed = parse_clamscan_output(clam_res.stdout)
204
+ clam_threats.extend(parsed)
205
+ threats.extend(clam_threats)
206
+ engine_results["clamav"] = {
207
+ "enabled": True,
208
+ "threats_found": len(clam_threats),
209
+ "status": "Completed",
210
+ }
211
+ else:
212
+ engine_results["clamav"] = {"enabled": False, "status": "clamscan not installed"}
213
+ else:
214
+ engine_results["clamav"] = {"enabled": False, "status": "Disabled"}
215
+
216
+ # 2. YARA Scan
217
+ if config.use_yara:
218
+ try:
219
+ import yara
220
+
221
+ rules = None
222
+ if config.yara_rules_path and Path(config.yara_rules_path).exists():
223
+ logger.info("Compiling custom YARA rules from %s", config.yara_rules_path)
224
+ rules = yara.compile(filepath=str(config.yara_rules_path))
225
+ else:
226
+ logger.info("Compiling built-in heuristic YARA rules")
227
+ rules = yara.compile(source=BUILTIN_HEURISTIC_YARA_RULES)
228
+
229
+ yara_threats = []
230
+ for t_path in scan_targets:
231
+ if not t_path.exists():
232
+ continue
233
+ if t_path.is_file():
234
+ files_to_scan = [t_path]
235
+ else:
236
+ files_to_scan = [
237
+ p for p in t_path.rglob("*")
238
+ if p.is_file() and p.stat().st_size < 25 * 1024 * 1024 # Skip >25MB
239
+ ][:500] # Cap at 500 files per directory in quick scan
240
+
241
+ for fp in files_to_scan:
242
+ scanned_files_count += 1
243
+ try:
244
+ matches = rules.match(str(fp))
245
+ for match in matches:
246
+ yara_threats.append({
247
+ "file": str(fp),
248
+ "rule": match.rule,
249
+ "tags": match.tags,
250
+ "meta": match.meta,
251
+ "engine": "yara",
252
+ })
253
+ except Exception:
254
+ continue
255
+
256
+ threats.extend(yara_threats)
257
+ engine_results["yara"] = {
258
+ "enabled": True,
259
+ "threats_found": len(yara_threats),
260
+ "files_scanned": scanned_files_count,
261
+ "status": "Completed",
262
+ }
263
+ except ImportError:
264
+ engine_results["yara"] = {"enabled": False, "status": "yara-python not installed"}
265
+ except Exception as exc:
266
+ engine_results["yara"] = {"enabled": True, "error": str(exc), "status": "Failed"}
267
+ else:
268
+ engine_results["yara"] = {"enabled": False, "status": "Disabled"}
269
+
270
+ # 3. VirusTotal Hash Reputation for detected threats or suspicious files
271
+ if config.use_virustotal and config.vt_api_key and not offline:
272
+ vt_checked = 0
273
+ for threat in threats[:10]: # Limit API requests to top 10
274
+ f_path = threat.get("file")
275
+ if f_path and Path(f_path).is_file():
276
+ sha256 = compute_sha256(f_path)
277
+ if sha256:
278
+ vt_res = query_virustotal_hash(sha256, config.vt_api_key)
279
+ threat["virustotal"] = vt_res
280
+ vt_checked += 1
281
+ engine_results["virustotal"] = {
282
+ "enabled": True,
283
+ "queries_executed": vt_checked,
284
+ "status": "Completed",
285
+ }
286
+ elif config.use_virustotal and offline:
287
+ engine_results["virustotal"] = {"enabled": False, "status": "Skipped (Offline Mode)"}
288
+ else:
289
+ engine_results["virustotal"] = {"enabled": False, "status": "Disabled"}
290
+
291
+ return {
292
+ "threats": threats,
293
+ "threat_count": len(threats),
294
+ "scanned_files": scanned_files_count,
295
+ "clean": len(threats) == 0,
296
+ "engine_results": engine_results,
297
+ }
298
+
299
+
300
+ def quarantine_file(
301
+ file_path: str | Path,
302
+ quarantine_dir: str | Path = "quarantine",
303
+ ) -> dict[str, Any]:
304
+ """
305
+ Move a suspicious file to a secure quarantine directory with metadata.
306
+ """
307
+ src = Path(file_path)
308
+ if not src.exists():
309
+ return {"success": False, "error": f"File {file_path} does not exist"}
310
+
311
+ q_dir = Path(quarantine_dir)
312
+ q_dir.mkdir(parents=True, exist_ok=True)
313
+
314
+ timestamp = int(time.time())
315
+ safe_name = f"{src.stem}_{timestamp}{src.suffix}.quarantine"
316
+ dst = q_dir / safe_name
317
+ meta_path = q_dir / f"{safe_name}.json"
318
+
319
+ file_hash = compute_sha256(src)
320
+
321
+ try:
322
+ shutil.move(str(src), str(dst))
323
+ meta = {
324
+ "original_path": str(src.resolve()),
325
+ "quarantined_name": safe_name,
326
+ "quarantine_time": timestamp,
327
+ "sha256": file_hash,
328
+ "file_size": dst.stat().st_size,
329
+ }
330
+ meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
331
+ logger.info("Quarantined %s to %s", src, dst)
332
+ return {
333
+ "success": True,
334
+ "source": str(src),
335
+ "quarantined_file": str(dst),
336
+ "meta_file": str(meta_path),
337
+ "sha256": file_hash,
338
+ }
339
+ except Exception as exc:
340
+ logger.error("Failed to quarantine %s: %s", src, exc)
341
+ return {"success": False, "error": str(exc)}
342
+
343
+
344
+ def list_quarantine(quarantine_dir: str | Path = "quarantine") -> list[dict[str, Any]]:
345
+ """
346
+ List all quarantined files and their metadata.
347
+ """
348
+ q_dir = Path(quarantine_dir)
349
+ if not q_dir.is_dir():
350
+ return []
351
+
352
+ items = []
353
+ for meta_file in q_dir.glob("*.json"):
354
+ try:
355
+ meta = json.loads(meta_file.read_text(encoding="utf-8"))
356
+ q_file = q_dir / meta.get("quarantined_name", "")
357
+ if q_file.exists():
358
+ meta["exists"] = True
359
+ meta["quarantined_path"] = str(q_file)
360
+ else:
361
+ meta["exists"] = False
362
+ items.append(meta)
363
+ except Exception:
364
+ continue
365
+ return items
366
+
367
+
368
+ def restore_quarantined_file(
369
+ quarantined_name: str,
370
+ quarantine_dir: str | Path = "quarantine",
371
+ ) -> dict[str, Any]:
372
+ """
373
+ Restore a quarantined file back to its original location.
374
+ """
375
+ q_dir = Path(quarantine_dir)
376
+ meta_file = q_dir / f"{quarantined_name}.json"
377
+ q_file = q_dir / quarantined_name
378
+
379
+ if not meta_file.exists() or not q_file.exists():
380
+ return {"success": False, "error": "Quarantine records not found"}
381
+
382
+ try:
383
+ meta = json.loads(meta_file.read_text(encoding="utf-8"))
384
+ original_path = Path(meta["original_path"])
385
+ original_path.parent.mkdir(parents=True, exist_ok=True)
386
+
387
+ shutil.move(str(q_file), str(original_path))
388
+ meta_file.unlink(missing_ok=True)
389
+ return {"success": True, "restored_path": str(original_path)}
390
+ except Exception as exc:
391
+ return {"success": False, "error": str(exc)}
392
+
393
+
394
+ def delete_quarantined_file(
395
+ quarantined_name: str,
396
+ quarantine_dir: str | Path = "quarantine",
397
+ ) -> dict[str, Any]:
398
+ """
399
+ Permanently delete a quarantined file and its metadata.
400
+ """
401
+ q_dir = Path(quarantine_dir)
402
+ meta_file = q_dir / f"{quarantined_name}.json"
403
+ q_file = q_dir / quarantined_name
404
+
405
+ success = False
406
+ if q_file.exists():
407
+ q_file.unlink(missing_ok=True)
408
+ success = True
409
+ if meta_file.exists():
410
+ meta_file.unlink(missing_ok=True)
411
+
412
+ return {"success": success, "deleted": quarantined_name}
@@ -0,0 +1,105 @@
1
+ # sysmaint/modules/memory.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ from typing import Any
8
+
9
+ import psutil
10
+
11
+ from ..utils.common import format_bytes
12
+
13
+ logger = logging.getLogger("sysmaint.memory")
14
+
15
+
16
+ def get_top_processes(limit: int = 10) -> list[dict[str, Any]]:
17
+ """
18
+ Return top processes ordered by RAM memory consumption.
19
+ """
20
+ procs = []
21
+ for proc in psutil.process_iter(["pid", "name", "memory_percent", "cpu_percent", "memory_info", "username"]):
22
+ try:
23
+ info = proc.info
24
+ rss = info["memory_info"].rss if info.get("memory_info") else 0
25
+ procs.append({
26
+ "pid": info["pid"],
27
+ "name": info["name"] or "Unknown",
28
+ "memory_percent": round(info.get("memory_percent") or 0.0, 1),
29
+ "cpu_percent": round(info.get("cpu_percent") or 0.0, 1),
30
+ "rss": rss,
31
+ "rss_formatted": format_bytes(rss),
32
+ "user": info.get("username") or "N/A",
33
+ })
34
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
35
+ continue
36
+
37
+ procs.sort(key=lambda x: x["rss"], reverse=True)
38
+ return procs[:limit]
39
+
40
+
41
+ def optimize_memory() -> dict[str, Any]:
42
+ """
43
+ Attempt to free unused memory by trimming process working sets (Windows) or dropping page caches (Linux).
44
+ """
45
+ system = platform.system().lower()
46
+ logger.info("Executing memory optimization for %s", system)
47
+
48
+ if system == "windows":
49
+ from ..utils.windows import trim_process_working_sets
50
+ count = trim_process_working_sets()
51
+ return {
52
+ "success": True,
53
+ "system": "windows",
54
+ "message": f"Trimmed working set memory on {count} active processes.",
55
+ "processes_trimmed": count,
56
+ }
57
+
58
+ if system == "linux":
59
+ from ..utils.linux import drop_linux_page_caches
60
+ success = drop_linux_page_caches()
61
+ return {
62
+ "success": success,
63
+ "system": "linux",
64
+ "message": "Dropped filesystem page caches and slab objects." if success else "Requires root to drop caches.",
65
+ }
66
+
67
+ return {"success": False, "message": f"Optimization not supported on {system}"}
68
+
69
+
70
+ def check_memory() -> dict[str, Any]:
71
+ """
72
+ Collect comprehensive memory, swap, and top process statistics.
73
+
74
+ Returns:
75
+ Dictionary with total/available/used/free, swap metrics, and top processes.
76
+ """
77
+ logger.info("Collecting system memory statistics")
78
+ virtual = psutil.virtual_memory()
79
+ swap = psutil.swap_memory()
80
+ top_processes = get_top_processes(limit=10)
81
+
82
+ # Health status based on memory pressure
83
+ is_critical = virtual.percent >= 90.0
84
+ is_warning = virtual.percent >= 80.0
85
+
86
+ return {
87
+ "total": virtual.total,
88
+ "available": virtual.available,
89
+ "used": virtual.used,
90
+ "free": virtual.free,
91
+ "percent": virtual.percent,
92
+ "total_formatted": format_bytes(virtual.total),
93
+ "available_formatted": format_bytes(virtual.available),
94
+ "used_formatted": format_bytes(virtual.used),
95
+ "free_formatted": format_bytes(virtual.free),
96
+ "swap_total": swap.total,
97
+ "swap_used": swap.used,
98
+ "swap_free": swap.free,
99
+ "swap_percent": swap.percent,
100
+ "swap_total_formatted": format_bytes(swap.total),
101
+ "swap_used_formatted": format_bytes(swap.used),
102
+ "swap_free_formatted": format_bytes(swap.free),
103
+ "status": "Critical" if is_critical else ("Warning" if is_warning else "Healthy"),
104
+ "top_processes": top_processes,
105
+ }
@@ -0,0 +1,167 @@
1
+ # sysmaint/modules/network.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ import socket
8
+ from typing import Any
9
+
10
+ import psutil
11
+
12
+ from ..utils.common import format_bytes, run_command
13
+ from ..utils.parsers import parse_ping_output
14
+
15
+ logger = logging.getLogger("sysmaint.network")
16
+
17
+
18
+ def get_network_interfaces() -> list[dict[str, Any]]:
19
+ """
20
+ Return all network adapters with IP addresses, MAC, status, and traffic stats.
21
+ """
22
+ interfaces = []
23
+ addrs = psutil.net_if_addrs()
24
+ stats = psutil.net_if_stats()
25
+ io_counters = psutil.net_io_counters(pernic=True)
26
+
27
+ for iface_name, addr_list in addrs.items():
28
+ stat = stats.get(iface_name)
29
+ io = io_counters.get(iface_name)
30
+
31
+ ipv4 = None
32
+ ipv6 = None
33
+ mac = None
34
+
35
+ for addr in addr_list:
36
+ if addr.family == socket.AF_INET:
37
+ ipv4 = addr.address
38
+ elif addr.family == socket.AF_INET6:
39
+ ipv6 = addr.address
40
+ elif getattr(psutil, "AF_LINK", None) and addr.family == psutil.AF_LINK:
41
+ mac = addr.address
42
+
43
+ is_up = stat.isup if stat else False
44
+ speed = stat.speed if stat else 0
45
+
46
+ # Skip virtual loopback if not active
47
+ if iface_name.lower().startswith("loopback") and not is_up:
48
+ continue
49
+
50
+ interfaces.append({
51
+ "name": iface_name,
52
+ "ipv4": ipv4 or "N/A",
53
+ "ipv6": ipv6 or "N/A",
54
+ "mac": mac or "N/A",
55
+ "is_up": is_up,
56
+ "speed_mbps": speed,
57
+ "bytes_sent_formatted": format_bytes(io.bytes_sent) if io else "0 B",
58
+ "bytes_recv_formatted": format_bytes(io.bytes_recv) if io else "0 B",
59
+ })
60
+
61
+ return interfaces
62
+
63
+
64
+ def test_connectivity(target_host: str = "1.1.1.1") -> dict[str, Any]:
65
+ """
66
+ Test network latency and packet loss by pinging a host.
67
+ """
68
+ system = platform.system().lower()
69
+ logger.info("Testing network latency to %s", target_host)
70
+
71
+ count_flag = "-n" if system == "windows" else "-c"
72
+ timeout_flag = "-w" if system == "windows" else "-W"
73
+ timeout_val = "2000" if system == "windows" else "2"
74
+
75
+ cmd = ["ping", count_flag, "3", timeout_flag, timeout_val, target_host]
76
+ result = run_command(cmd, check=False)
77
+ parsed = parse_ping_output(result.stdout)
78
+ parsed["target"] = target_host
79
+ return parsed
80
+
81
+
82
+ def flush_dns() -> dict[str, Any]:
83
+ """
84
+ Flush DNS resolver caches across Windows or Linux.
85
+ """
86
+ system = platform.system().lower()
87
+ logger.info("Flushing DNS resolver cache on %s", system)
88
+
89
+ if system == "windows":
90
+ from ..utils.windows import flush_windows_dns
91
+ success = flush_windows_dns()
92
+ return {
93
+ "success": success,
94
+ "system": "windows",
95
+ "message": "Flushed Windows DNS Resolver Cache successfully." if success else "Failed to flush DNS cache.",
96
+ }
97
+
98
+ if system == "linux":
99
+ from ..utils.linux import flush_linux_dns
100
+ success = flush_linux_dns()
101
+ return {
102
+ "success": success,
103
+ "system": "linux",
104
+ "message": "Flushed Linux DNS cache." if success else "Could not flush DNS (requires resolvectl/systemd-resolve).",
105
+ }
106
+
107
+ return {"success": False, "message": f"Unsupported platform: {system}"}
108
+
109
+
110
+ def get_listening_ports(limit: int = 50) -> list[dict[str, Any]]:
111
+ """
112
+ List active listening network sockets and their associated processes.
113
+ """
114
+ ports = []
115
+ try:
116
+ connections = psutil.net_connections(kind="inet")
117
+ for conn in connections:
118
+ if conn.status == psutil.CONN_LISTEN:
119
+ laddr = f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else "N/A"
120
+ proc_name = "System"
121
+ if conn.pid:
122
+ try:
123
+ proc = psutil.Process(conn.pid)
124
+ proc_name = proc.name()
125
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
126
+ proc_name = f"PID {conn.pid}"
127
+
128
+ ports.append({
129
+ "protocol": "TCP" if conn.type == socket.SOCK_STREAM else "UDP",
130
+ "local_address": laddr,
131
+ "pid": conn.pid,
132
+ "process_name": proc_name,
133
+ })
134
+ except (psutil.AccessDenied, PermissionError):
135
+ logger.debug("Access denied reading net_connections (run as admin for full port list)")
136
+
137
+ return ports[:limit]
138
+
139
+
140
+ def reset_network_stack(dry_run: bool = False) -> dict[str, Any]:
141
+ """Repair corrupted network stack (Winsock/TCP-IP reset on Windows, NetworkManager on Linux)."""
142
+ system = platform.system().lower()
143
+ if system == "windows":
144
+ cmds = [
145
+ ["ipconfig", "/flushdns"],
146
+ ["netsh", "winsock", "reset"],
147
+ ["netsh", "int", "ip", "reset"],
148
+ ]
149
+ if dry_run:
150
+ return {"dry_run": True, "system": "windows", "commands": [" ".join(c) for c in cmds]}
151
+ outputs = []
152
+ for cmd in cmds:
153
+ res = run_command(cmd, check=False)
154
+ outputs.append({"command": " ".join(cmd), "returncode": res.returncode, "output": res.stdout.strip()})
155
+ return {"system": "windows", "status": "reset_complete", "steps": outputs}
156
+
157
+ if system == "linux":
158
+ import shutil
159
+ if shutil.which("systemctl"):
160
+ cmd = ["systemctl", "restart", "NetworkManager"]
161
+ if dry_run:
162
+ return {"dry_run": True, "system": "linux", "commands": [" ".join(cmd)]}
163
+ res = run_command(cmd, check=False)
164
+ return {"system": "linux", "returncode": res.returncode, "output": res.stdout.strip()}
165
+ return {"system": "linux", "error": "systemctl not available"}
166
+
167
+ return {"error": f"Unsupported platform: {system}"}