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,232 @@
1
+ # sysmaint/modules/report.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import platform
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ def build_report(results: dict[str, Any]) -> dict[str, Any]:
13
+ """
14
+ Build a structured report dictionary.
15
+
16
+ Args:
17
+ results: Dictionary of results produced by the executed command.
18
+
19
+ Returns:
20
+ Report dictionary with timestamp, OS, and results.
21
+ """
22
+ return {
23
+ "timestamp": datetime.now(timezone.utc).isoformat(),
24
+ "os": platform.system(),
25
+ "os_release": platform.release(),
26
+ "hostname": platform.node(),
27
+ "results": results,
28
+ }
29
+
30
+
31
+ def format_report(report: dict[str, Any], json_output: bool = False) -> str:
32
+ """
33
+ Format a report as JSON or structured human-readable text.
34
+
35
+ Args:
36
+ report: Report dictionary from build_report().
37
+ json_output: If True, return pretty-printed JSON.
38
+
39
+ Returns:
40
+ Formatted report string.
41
+ """
42
+ if json_output:
43
+ return json.dumps(report, indent=2, default=str)
44
+
45
+ lines = [
46
+ "=" * 60,
47
+ " SysMaint - System Maintenance Report",
48
+ "=" * 60,
49
+ f" Timestamp : {report.get('timestamp', 'unknown')}",
50
+ f" Host : {report.get('hostname', 'unknown')}",
51
+ f" OS : {report.get('os', 'unknown')} {report.get('os_release', '')}",
52
+ "-" * 60,
53
+ " RESULTS SUMMARY:",
54
+ "-" * 60,
55
+ ]
56
+
57
+ results = report.get("results", {})
58
+ if not results:
59
+ lines.append(" (No operations executed)")
60
+
61
+ for section, data in results.items():
62
+ if isinstance(data, dict):
63
+ if "error" in data:
64
+ lines.append(f" [!] {section.upper()}: ERROR - {data['error']}")
65
+ elif "message" in data:
66
+ lines.append(f" [*] {section.upper()}: {data['message']}")
67
+ else:
68
+ lines.append(f" [*] {section.upper()}:")
69
+ for k, v in data.items():
70
+ if k not in ("output", "stderr", "raw", "data"):
71
+ lines.append(f" - {k}: {v}")
72
+ else:
73
+ lines.append(f" [*] {section.upper()}: {data}")
74
+
75
+ lines.append("=" * 60)
76
+ return "\n".join(lines)
77
+
78
+
79
+ def generate_html_report(
80
+ report: dict[str, Any],
81
+ output_path: str | Path | None = None,
82
+ ) -> str:
83
+ """
84
+ Generate a modern, responsive standalone HTML health report dashboard.
85
+
86
+ Args:
87
+ report: Report dictionary.
88
+ output_path: Optional file path to save HTML to.
89
+
90
+ Returns:
91
+ HTML string.
92
+ """
93
+ timestamp = report.get("timestamp", datetime.now(timezone.utc).isoformat())
94
+ host = report.get("hostname", platform.node())
95
+ os_name = f"{report.get('os', platform.system())} {report.get('os_release', '')}"
96
+ results = report.get("results", {})
97
+
98
+ # Extract health score if present
99
+ health_score = 100
100
+ health_grade = "Good"
101
+ if "smart_scan" in results and isinstance(results["smart_scan"], dict):
102
+ health_score = results["smart_scan"].get("health_score", 100)
103
+ health_grade = results["smart_scan"].get("health_grade", "Good")
104
+ elif "optimizer" in results and isinstance(results["optimizer"], dict):
105
+ health_score = results["optimizer"].get("new_health_score", 100)
106
+ health_grade = results["optimizer"].get("new_health_grade", "Good")
107
+
108
+ score_color = "#10b981" if health_score >= 85 else ("#3b82f6" if health_score >= 70 else ("#f59e0b" if health_score >= 50 else "#ef4444"))
109
+
110
+ # Render section cards
111
+ sections_html = []
112
+ for sec_name, data in results.items():
113
+ content_items = []
114
+ if isinstance(data, dict):
115
+ for k, v in data.items():
116
+ if k in ("output", "stderr", "raw", "data") or isinstance(v, (dict, list)):
117
+ continue
118
+ content_items.append(f"<div class='metric-row'><span class='metric-key'>{k.replace('_', ' ').capitalize()}</span><span class='metric-val'>{v}</span></div>")
119
+ else:
120
+ content_items.append(f"<div class='metric-row'><span>{data}</span></div>")
121
+
122
+ items_str = "".join(content_items) or "<div class='metric-row'><span>Completed successfully</span></div>"
123
+ sections_html.append(f"""
124
+ <div class="card">
125
+ <div class="card-header">
126
+ <h3>{sec_name.replace('_', ' ').upper()}</h3>
127
+ </div>
128
+ <div class="card-body">
129
+ {items_str}
130
+ </div>
131
+ </div>
132
+ """)
133
+
134
+ sections_str = "".join(sections_html)
135
+
136
+ html = f"""<!DOCTYPE html>
137
+ <html lang="en">
138
+ <head>
139
+ <meta charset="UTF-8">
140
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
141
+ <title>SysMaint Health Report - {host}</title>
142
+ <style>
143
+ :root {{
144
+ --bg-primary: #0f172a;
145
+ --bg-secondary: #1e293b;
146
+ --bg-card: #1e293b;
147
+ --text-primary: #f8fafc;
148
+ --text-secondary: #94a3b8;
149
+ --accent: #38bdf8;
150
+ --accent-gradient: linear-gradient(135deg, #38bdf8 0%, #818cf8 100%);
151
+ --border: #334155;
152
+ --success: #10b981;
153
+ --warning: #f59e0b;
154
+ --danger: #ef4444;
155
+ }}
156
+ * {{ margin: 0; padding: 0; box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }}
157
+ body {{ background-color: var(--bg-primary); color: var(--text-primary); padding: 2rem; line-height: 1.6; }}
158
+ .container {{ max-width: 1100px; margin: 0 auto; }}
159
+ .header {{ display: flex; justify-content: space-between; align-items: center; padding-bottom: 2rem; border-bottom: 1px solid var(--border); margin-bottom: 2rem; }}
160
+ .header h1 {{ font-size: 2rem; background: var(--accent-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }}
161
+ .header .meta {{ color: var(--text-secondary); font-size: 0.9rem; text-align: right; }}
162
+ .hero {{ display: grid; grid-template-columns: 260px 1fr; gap: 1.5rem; margin-bottom: 2rem; }}
163
+ .score-card {{ background: var(--bg-secondary); border-radius: 16px; border: 1px solid var(--border); padding: 2rem; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; }}
164
+ .score-circle {{ width: 130px; height: 130px; border-radius: 50%; border: 8px solid {score_color}; display: flex; flex-direction: column; align-items: center; justify-content: center; margin-bottom: 1rem; box-shadow: 0 0 20px {score_color}33; }}
165
+ .score-number {{ font-size: 2.5rem; font-weight: 800; color: {score_color}; }}
166
+ .score-grade {{ font-size: 1rem; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 1px; }}
167
+ .system-card {{ background: var(--bg-secondary); border-radius: 16px; border: 1px solid var(--border); padding: 1.5rem; }}
168
+ .system-card h2 {{ font-size: 1.25rem; margin-bottom: 1rem; color: var(--accent); }}
169
+ .grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1.5rem; }}
170
+ .card {{ background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border); overflow: hidden; }}
171
+ .card-header {{ background: rgba(255,255,255,0.03); padding: 1rem 1.25rem; border-bottom: 1px solid var(--border); }}
172
+ .card-header h3 {{ font-size: 1rem; letter-spacing: 0.5px; color: var(--accent); }}
173
+ .card-body {{ padding: 1.25rem; }}
174
+ .metric-row {{ display: flex; justify-content: space-between; padding: 0.5rem 0; border-bottom: 1px solid rgba(255,255,255,0.05); font-size: 0.9rem; }}
175
+ .metric-row:last-child {{ border-bottom: none; }}
176
+ .metric-key {{ color: var(--text-secondary); }}
177
+ .metric-val {{ font-weight: 600; }}
178
+ .footer {{ text-align: center; margin-top: 3rem; color: var(--text-secondary); font-size: 0.85rem; padding-top: 1.5rem; border-top: 1px solid var(--border); }}
179
+ @media print {{
180
+ body {{ background: #fff; color: #000; padding: 1rem; }}
181
+ .card, .score-card, .system-card {{ border: 1px solid #ccc; background: #fff; color: #000; box-shadow: none; }}
182
+ .header h1 {{ color: #000; -webkit-text-fill-color: #000; }}
183
+ }}
184
+ </style>
185
+ </head>
186
+ <body>
187
+ <div class="container">
188
+ <div class="header">
189
+ <div>
190
+ <h1>SysMaint System Health Report</h1>
191
+ <p style="color: var(--text-secondary); margin-top: 0.25rem;">Automated Diagnostic & Maintenance Telemetry</p>
192
+ </div>
193
+ <div class="meta">
194
+ <div><strong>Host:</strong> {host}</div>
195
+ <div><strong>OS:</strong> {os_name}</div>
196
+ <div><strong>Date:</strong> {timestamp[:19].replace('T', ' ')} UTC</div>
197
+ </div>
198
+ </div>
199
+
200
+ <div class="hero">
201
+ <div class="score-card">
202
+ <div class="score-circle">
203
+ <div class="score-number">{health_score}</div>
204
+ </div>
205
+ <div class="score-grade">{health_grade} Condition</div>
206
+ </div>
207
+ <div class="system-card">
208
+ <h2>System Overview</h2>
209
+ <div class="metric-row"><span class="metric-key">Host Node</span><span class="metric-val">{host}</span></div>
210
+ <div class="metric-row"><span class="metric-key">Operating System</span><span class="metric-val">{os_name}</span></div>
211
+ <div class="metric-row"><span class="metric-key">Report Generated</span><span class="metric-val">{timestamp}</span></div>
212
+ <div class="metric-row"><span class="metric-key">Status</span><span class="metric-val" style="color: {score_color}; font-weight: bold;">Verified</span></div>
213
+ </div>
214
+ </div>
215
+
216
+ <div class="grid">
217
+ {sections_str}
218
+ </div>
219
+
220
+ <div class="footer">
221
+ <p>Generated by <strong>SysMaint Toolkit</strong> • Cross-Platform System Maintenance Suite</p>
222
+ </div>
223
+ </div>
224
+ </body>
225
+ </html>
226
+ """
227
+ if output_path:
228
+ out = Path(output_path)
229
+ out.parent.mkdir(parents=True, exist_ok=True)
230
+ out.write_text(html, encoding="utf-8")
231
+
232
+ return html
@@ -0,0 +1,123 @@
1
+ # sysmaint/modules/restore.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from ..config import SysMaintConfig
11
+ from ..utils.common import format_bytes, run_command
12
+
13
+ logger = logging.getLogger("sysmaint.restore")
14
+
15
+
16
+ def list_available_backups(config: SysMaintConfig) -> list[dict[str, Any]]:
17
+ """
18
+ List all available System Restore points or backup archives.
19
+ """
20
+ system = platform.system().lower()
21
+ backups: list[dict[str, Any]] = []
22
+
23
+ if system == "windows":
24
+ from ..utils import windows
25
+ try:
26
+ points = windows.list_restore_points()
27
+ for pt in points:
28
+ backups.append({
29
+ "id": str(pt.get("sequence_number")),
30
+ "name": pt.get("description", "Restore Point"),
31
+ "type": "Windows System Restore Point",
32
+ "date": pt.get("time"),
33
+ "can_restore": True,
34
+ })
35
+ except Exception as exc:
36
+ logger.debug("Failed to list Windows restore points: %s", exc)
37
+
38
+ # Also list local file backups
39
+ backup_dir = Path(config.repair.backup_dir)
40
+ if backup_dir.is_dir():
41
+ for f in backup_dir.glob("sysmaint-*"):
42
+ if f.is_file():
43
+ size = f.stat().st_size
44
+ backups.append({
45
+ "id": f.name,
46
+ "name": f.name,
47
+ "type": "Archive / Backup File",
48
+ "path": str(f.resolve()),
49
+ "size_formatted": format_bytes(size),
50
+ "can_restore": True,
51
+ })
52
+
53
+ return backups
54
+
55
+
56
+ def launch_system_recovery() -> dict[str, Any]:
57
+ """
58
+ Launch native OS recovery / System Restore wizard.
59
+ """
60
+ system = platform.system().lower()
61
+ if system == "windows":
62
+ # Launch Windows System Restore UI (rstrui.exe)
63
+ run_command(["rstrui.exe"], check=False)
64
+ return {
65
+ "success": True,
66
+ "message": "Launched Windows System Restore UI (rstrui.exe)",
67
+ }
68
+ return {
69
+ "success": False,
70
+ "message": f"Interactive recovery UI not supported on {system}",
71
+ }
72
+
73
+
74
+ def restore_backup(
75
+ config: SysMaintConfig,
76
+ backup_ref: str,
77
+ kind: str = "auto",
78
+ ) -> dict[str, Any]:
79
+ """
80
+ Restore system from a specified backup reference.
81
+
82
+ Args:
83
+ config: SysMaintConfig instance.
84
+ backup_ref: Backup file name or restore point identifier.
85
+ kind: 'auto', 'restore-point', 'tar', or 'snapshot'.
86
+
87
+ Returns:
88
+ Dictionary with restoration result and details.
89
+ """
90
+ system = platform.system().lower()
91
+ logger.info("Restore requested: kind=%s, ref=%s", kind, backup_ref)
92
+
93
+ if system == "windows" and (kind == "restore-point" or backup_ref.isdigit()):
94
+ return {
95
+ "restored": False,
96
+ "requires_reboot": True,
97
+ "message": (
98
+ f"To restore Windows Restore Point #{backup_ref}, please use Windows Recovery (rstrui.exe) "
99
+ "or Advanced Startup Options to ensure system state integrity."
100
+ ),
101
+ "reference": backup_ref,
102
+ }
103
+
104
+ # Tarball restore on Linux
105
+ if system == "linux" and backup_ref.endswith(".tar.gz"):
106
+ backup_file = Path(config.repair.backup_dir) / backup_ref
107
+ if not backup_file.exists():
108
+ backup_file = Path(backup_ref)
109
+
110
+ if backup_file.exists():
111
+ res = run_command(["tar", "-xzf", str(backup_file), "-C", "/"], check=False)
112
+ return {
113
+ "restored": res.returncode == 0,
114
+ "file": str(backup_file),
115
+ "error": res.stderr if res.returncode != 0 else None,
116
+ "message": "Extracted backup archive to root filesystem." if res.returncode == 0 else "Extraction failed.",
117
+ }
118
+
119
+ return {
120
+ "restored": False,
121
+ "message": "Automated restore requires specific reference and user confirmation.",
122
+ "reference": backup_ref,
123
+ }
@@ -0,0 +1,137 @@
1
+ # sysmaint/modules/scheduler.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ import sys
8
+ from typing import Any
9
+
10
+ from ..utils.common import run_command
11
+
12
+ logger = logging.getLogger("sysmaint.scheduler")
13
+
14
+ TASK_NAME = "SysMaintAutomatedMaintenance"
15
+
16
+
17
+ def get_schedule_status() -> dict[str, Any]:
18
+ """
19
+ Check if SysMaint automated maintenance is currently scheduled.
20
+ """
21
+ system = platform.system().lower()
22
+ logger.info("Checking maintenance schedule status for %s", system)
23
+
24
+ if system == "windows":
25
+ res = run_command(["schtasks", "/Query", "/TN", TASK_NAME, "/FO", "LIST"], check=False)
26
+ is_installed = res.returncode == 0 and "TaskName:" in res.stdout
27
+ return {
28
+ "system": "windows",
29
+ "installed": is_installed,
30
+ "task_name": TASK_NAME,
31
+ "details": res.stdout.strip() if is_installed else "Task not scheduled",
32
+ }
33
+
34
+ if system == "linux":
35
+ res = run_command(["crontab", "-l"], check=False)
36
+ is_installed = "sysmaint" in res.stdout
37
+ return {
38
+ "system": "linux",
39
+ "installed": is_installed,
40
+ "details": [line for line in res.stdout.splitlines() if "sysmaint" in line] if is_installed else [],
41
+ }
42
+
43
+ return {"system": system, "installed": False}
44
+
45
+
46
+ def install_schedule(
47
+ interval: str = "WEEKLY",
48
+ time_str: str = "02:00",
49
+ command_flag: str = "smart-scan",
50
+ ) -> dict[str, Any]:
51
+ """
52
+ Install an automated background maintenance task.
53
+
54
+ Args:
55
+ interval: 'DAILY', 'WEEKLY', or 'MONTHLY'.
56
+ time_str: Time in HH:MM (24-hour) format.
57
+ command_flag: Subcommand to run, e.g. 'smart-scan' or 'clean'.
58
+
59
+ Returns:
60
+ Dictionary indicating status.
61
+ """
62
+ system = platform.system().lower()
63
+ py_exec = sys.executable
64
+ maint_cmd = f'"{py_exec}" -m sysmaint {command_flag} --yes'
65
+
66
+ logger.info("Installing maintenance schedule (%s at %s)", interval, time_str)
67
+
68
+ if system == "windows":
69
+ # schtasks /Create /SC WEEKLY /TN SysMaintAutomatedMaintenance /TR "python -m sysmaint smart-scan --yes" /ST 02:00 /F /RL HIGHEST
70
+ cmd = [
71
+ "schtasks",
72
+ "/Create",
73
+ "/SC",
74
+ interval.upper(),
75
+ "/TN",
76
+ TASK_NAME,
77
+ "/TR",
78
+ maint_cmd,
79
+ "/ST",
80
+ time_str,
81
+ "/F",
82
+ "/RL",
83
+ "HIGHEST",
84
+ ]
85
+ res = run_command(cmd, check=False)
86
+ return {
87
+ "success": res.returncode == 0,
88
+ "system": "windows",
89
+ "message": "Scheduled task created successfully in Windows Task Scheduler." if res.returncode == 0 else f"Failed to create task: {res.stderr.strip()}",
90
+ }
91
+
92
+ if system == "linux":
93
+ # Determine cron schedule
94
+ hh, mm = time_str.split(":") if ":" in time_str else ("02", "00")
95
+ if interval.upper() == "DAILY":
96
+ cron_expr = f"{mm} {hh} * * *"
97
+ elif interval.upper() == "MONTHLY":
98
+ cron_expr = f"{mm} {hh} 1 * *"
99
+ else: # WEEKLY
100
+ cron_expr = f"{mm} {hh} * * 0"
101
+
102
+ cron_line = f"{cron_expr} {maint_cmd} > /var/log/sysmaint-cron.log 2>&1 # sysmaint"
103
+
104
+ existing = run_command(["crontab", "-l"], check=False).stdout
105
+ filtered = [l for l in existing.splitlines() if "sysmaint" not in l]
106
+ filtered.append(cron_line)
107
+
108
+ run_command(["crontab", "-"], check=False)
109
+ return {
110
+ "success": True,
111
+ "system": "linux",
112
+ "message": f"Installed cron schedule: '{cron_expr}'",
113
+ }
114
+
115
+ return {"success": False, "message": f"Unsupported platform: {system}"}
116
+
117
+
118
+ def remove_schedule() -> dict[str, Any]:
119
+ """
120
+ Remove any configured automated maintenance schedules.
121
+ """
122
+ system = platform.system().lower()
123
+ logger.info("Removing maintenance schedule")
124
+
125
+ if system == "windows":
126
+ res = run_command(["schtasks", "/Delete", "/TN", TASK_NAME, "/F"], check=False)
127
+ return {
128
+ "success": res.returncode == 0,
129
+ "message": "Removed Windows scheduled task." if res.returncode == 0 else "No scheduled task found to remove.",
130
+ }
131
+
132
+ if system == "linux":
133
+ run_command(["crontab", "-l"], check=False)
134
+ run_command(["crontab", "-"], check=False)
135
+ return {"success": True, "message": "Removed sysmaint cron jobs."}
136
+
137
+ return {"success": False, "message": f"Unsupported platform: {system}"}
@@ -0,0 +1,88 @@
1
+ # sysmaint/modules/security.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ import shutil
8
+ from typing import Any
9
+
10
+ from ..utils.escalate import is_elevated
11
+
12
+ logger = logging.getLogger("sysmaint.security")
13
+
14
+
15
+ def audit_security_posture() -> dict[str, Any]:
16
+ """
17
+ Perform a security posture audit (Antivirus, Firewall, UAC/Sudo elevation).
18
+
19
+ Returns:
20
+ Dictionary with security scores, status flags, and actionable recommendations.
21
+ """
22
+ system = platform.system().lower()
23
+ logger.info("Auditing security posture for %s", system)
24
+
25
+ issues: list[str] = []
26
+ score = 100
27
+
28
+ elevated = is_elevated()
29
+ if not elevated:
30
+ issues.append("Toolkit is running in unprivileged user mode. Some deep security audits require Admin/root.")
31
+
32
+ if system == "windows":
33
+ from ..utils.windows import get_windows_security_status
34
+ sec = get_windows_security_status()
35
+
36
+ if not sec.get("realtime_protection", True):
37
+ issues.append("Windows Defender Real-time Protection appears to be disabled!")
38
+ score -= 30
39
+
40
+ if not sec.get("firewall_enabled", True):
41
+ issues.append("One or more Windows Firewall profiles are turned OFF.")
42
+ score -= 25
43
+
44
+ return {
45
+ "system": "windows",
46
+ "score": max(0, score),
47
+ "elevated": elevated,
48
+ "antivirus": sec.get("antivirus", "Windows Defender"),
49
+ "realtime_protection": sec.get("realtime_protection", True),
50
+ "firewall_active": sec.get("firewall_enabled", True),
51
+ "firewall_profiles": sec.get("firewall_profiles", []),
52
+ "issues": issues,
53
+ "healthy": len(issues) == 0,
54
+ }
55
+
56
+ if system == "linux":
57
+ from ..utils.linux import get_linux_security_status
58
+ sec = get_linux_security_status()
59
+
60
+ if not sec.get("firewall_active", False):
61
+ issues.append(f"Linux Firewall ({sec.get('firewall', 'iptables/ufw')}) is inactive or unconfigured.")
62
+ score -= 25
63
+
64
+ has_clamav = bool(shutil.which("clamscan"))
65
+ if not has_clamav:
66
+ issues.append("ClamAV antivirus engine is not installed.")
67
+ score -= 10
68
+
69
+ return {
70
+ "system": "linux",
71
+ "score": max(0, score),
72
+ "elevated": elevated,
73
+ "firewall": sec.get("firewall", "Unknown"),
74
+ "firewall_active": sec.get("firewall_active", False),
75
+ "mac_system": sec.get("mac_system", "None"),
76
+ "mac_enforcing": sec.get("mac_enforcing", False),
77
+ "clamav_installed": has_clamav,
78
+ "issues": issues,
79
+ "healthy": len(issues) == 0,
80
+ }
81
+
82
+ return {
83
+ "system": system,
84
+ "score": 80,
85
+ "elevated": elevated,
86
+ "issues": issues,
87
+ "healthy": True,
88
+ }