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.
- sysmaint/__init__.py +17 -0
- sysmaint/__main__.py +6 -0
- sysmaint/cli.py +637 -0
- sysmaint/config.py +229 -0
- sysmaint/gui/__init__.py +5 -0
- sysmaint/gui/app.py +193 -0
- sysmaint/gui/components/__init__.py +13 -0
- sysmaint/gui/components/cards.py +239 -0
- sysmaint/gui/components/console.py +61 -0
- sysmaint/gui/components/dialogs.py +79 -0
- sysmaint/gui/theme.py +52 -0
- sysmaint/gui/views/__init__.py +25 -0
- sysmaint/gui/views/backup.py +167 -0
- sysmaint/gui/views/cleaner.py +227 -0
- sysmaint/gui/views/dashboard.py +252 -0
- sysmaint/gui/views/diagnostics.py +243 -0
- sysmaint/gui/views/integrity.py +158 -0
- sysmaint/gui/views/malware.py +293 -0
- sysmaint/gui/views/network.py +171 -0
- sysmaint/gui/views/security.py +118 -0
- sysmaint/gui/views/settings.py +211 -0
- sysmaint/gui/views/startup.py +133 -0
- sysmaint/logging_setup.py +62 -0
- sysmaint/modules/__init__.py +41 -0
- sysmaint/modules/backup.py +106 -0
- sysmaint/modules/cleaner.py +249 -0
- sysmaint/modules/disk.py +160 -0
- sysmaint/modules/drivers.py +89 -0
- sysmaint/modules/integrity.py +148 -0
- sysmaint/modules/malware.py +412 -0
- sysmaint/modules/memory.py +105 -0
- sysmaint/modules/network.py +167 -0
- sysmaint/modules/optimizer.py +186 -0
- sysmaint/modules/recovery.py +353 -0
- sysmaint/modules/report.py +232 -0
- sysmaint/modules/restore.py +123 -0
- sysmaint/modules/scheduler.py +137 -0
- sysmaint/modules/security.py +88 -0
- sysmaint/modules/services.py +171 -0
- sysmaint/modules/startup.py +95 -0
- sysmaint/modules/sysinfo.py +112 -0
- sysmaint/service/__init__.py +5 -0
- sysmaint/service/server.py +210 -0
- sysmaint/tui/__init__.py +5 -0
- sysmaint/tui/app.py +830 -0
- sysmaint/tui/modals.py +201 -0
- sysmaint/tui/themes.py +97 -0
- sysmaint/utils/__init__.py +39 -0
- sysmaint/utils/common.py +255 -0
- sysmaint/utils/escalate.py +93 -0
- sysmaint/utils/linux.py +240 -0
- sysmaint/utils/parsers.py +171 -0
- sysmaint/utils/windows.py +308 -0
- sysmaint-0.1.0.dist-info/METADATA +307 -0
- sysmaint-0.1.0.dist-info/RECORD +57 -0
- sysmaint-0.1.0.dist-info/WHEEL +4 -0
- sysmaint-0.1.0.dist-info/entry_points.txt +5 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# sysmaint/modules/services.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import platform
|
|
7
|
+
import shutil
|
|
8
|
+
from collections.abc import Iterable
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import psutil
|
|
12
|
+
|
|
13
|
+
from ..utils.common import run_command
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("sysmaint.services")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def list_services() -> list[dict[str, Any]]:
|
|
19
|
+
"""
|
|
20
|
+
List all installed services across Windows or Linux safely.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
A list of dictionaries with service name, display name, status, and description.
|
|
24
|
+
"""
|
|
25
|
+
system = platform.system().lower()
|
|
26
|
+
logger.info("Enumerating services on %s", system)
|
|
27
|
+
services: list[dict[str, Any]] = []
|
|
28
|
+
|
|
29
|
+
if system == "windows":
|
|
30
|
+
for svc in psutil.win_service_iter():
|
|
31
|
+
try:
|
|
32
|
+
name = svc.name()
|
|
33
|
+
display_name = svc.display_name()
|
|
34
|
+
status = svc.status()
|
|
35
|
+
start_type = svc.start_type()
|
|
36
|
+
services.append({
|
|
37
|
+
"name": name,
|
|
38
|
+
"display_name": display_name,
|
|
39
|
+
"status": status,
|
|
40
|
+
"start_type": start_type,
|
|
41
|
+
"healthy": status != "stopped" or start_type != "automatic",
|
|
42
|
+
})
|
|
43
|
+
except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
|
|
44
|
+
continue
|
|
45
|
+
return sorted(services, key=lambda x: x["name"].lower())
|
|
46
|
+
|
|
47
|
+
if system == "linux":
|
|
48
|
+
if shutil.which("systemctl"):
|
|
49
|
+
result = run_command(
|
|
50
|
+
["systemctl", "list-units", "--type=service", "--all", "--no-pager", "--no-legend"],
|
|
51
|
+
check=False,
|
|
52
|
+
)
|
|
53
|
+
for line in result.stdout.splitlines():
|
|
54
|
+
parts = line.strip().split(None, 4)
|
|
55
|
+
if len(parts) >= 4:
|
|
56
|
+
unit_name = parts[0].replace(".service", "")
|
|
57
|
+
active_state = parts[2]
|
|
58
|
+
sub_state = parts[3]
|
|
59
|
+
desc = parts[4] if len(parts) > 4 else ""
|
|
60
|
+
is_failed = active_state == "failed"
|
|
61
|
+
services.append({
|
|
62
|
+
"name": unit_name,
|
|
63
|
+
"display_name": desc or unit_name,
|
|
64
|
+
"status": active_state,
|
|
65
|
+
"sub_status": sub_state,
|
|
66
|
+
"healthy": not is_failed,
|
|
67
|
+
})
|
|
68
|
+
return sorted(services, key=lambda x: x["name"].lower())
|
|
69
|
+
|
|
70
|
+
return []
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def service_status(name: str) -> str:
|
|
74
|
+
"""
|
|
75
|
+
Return the current status of a single service ('running', 'stopped', 'failed', 'not_found').
|
|
76
|
+
"""
|
|
77
|
+
system = platform.system().lower()
|
|
78
|
+
logger.info("Checking service status: %s", name)
|
|
79
|
+
|
|
80
|
+
if system == "windows":
|
|
81
|
+
try:
|
|
82
|
+
svc = psutil.win_service_get(name)
|
|
83
|
+
return svc.status()
|
|
84
|
+
except (psutil.NoSuchProcess, Exception):
|
|
85
|
+
return "not_found"
|
|
86
|
+
|
|
87
|
+
if system == "linux":
|
|
88
|
+
if shutil.which("systemctl"):
|
|
89
|
+
res = run_command(["systemctl", "is-active", name], check=False)
|
|
90
|
+
status = res.stdout.strip()
|
|
91
|
+
if status in ("active", "running"):
|
|
92
|
+
return "running"
|
|
93
|
+
elif status == "failed":
|
|
94
|
+
return "failed"
|
|
95
|
+
elif status in ("inactive", "dead"):
|
|
96
|
+
return "stopped"
|
|
97
|
+
return "unknown"
|
|
98
|
+
|
|
99
|
+
return "unsupported"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def control_service(name: str, action: str) -> dict[str, Any]:
|
|
103
|
+
"""
|
|
104
|
+
Start, stop, or restart a system service.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
name: Service identifier name.
|
|
108
|
+
action: One of 'start', 'stop', 'restart', 'enable', 'disable'.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
Dictionary with execution result.
|
|
112
|
+
"""
|
|
113
|
+
system = platform.system().lower()
|
|
114
|
+
logger.info("Performing service action '%s' on '%s'", action, name)
|
|
115
|
+
|
|
116
|
+
if system == "windows":
|
|
117
|
+
if action in ("start", "stop", "restart"):
|
|
118
|
+
# Use PowerShell Start-Service / Stop-Service / Restart-Service for synchronous reliability
|
|
119
|
+
ps_map = {
|
|
120
|
+
"start": f"Start-Service -Name '{name}'",
|
|
121
|
+
"stop": f"Stop-Service -Name '{name}' -Force",
|
|
122
|
+
"restart": f"Restart-Service -Name '{name}' -Force",
|
|
123
|
+
}
|
|
124
|
+
script = ps_map.get(action, f"sc {action} '{name}'")
|
|
125
|
+
cmd = ["powershell", "-NoProfile", "-Command", script]
|
|
126
|
+
elif action in ("enable", "disable"):
|
|
127
|
+
startup_type = "Automatic" if action == "enable" else "Disabled"
|
|
128
|
+
cmd = ["powershell", "-NoProfile", "-Command", f"Set-Service -Name '{name}' -StartupType {startup_type}"]
|
|
129
|
+
else:
|
|
130
|
+
return {"error": f"Invalid action: {action}"}
|
|
131
|
+
|
|
132
|
+
elif system == "linux":
|
|
133
|
+
if action in ("start", "stop", "restart", "enable", "disable"):
|
|
134
|
+
cmd = ["systemctl", action, name]
|
|
135
|
+
else:
|
|
136
|
+
return {"error": f"Invalid action: {action}"}
|
|
137
|
+
else:
|
|
138
|
+
return {"error": f"Unsupported platform: {system}"}
|
|
139
|
+
|
|
140
|
+
result = run_command(cmd, check=False)
|
|
141
|
+
return {
|
|
142
|
+
"name": name,
|
|
143
|
+
"action": action,
|
|
144
|
+
"success": result.returncode == 0,
|
|
145
|
+
"returncode": result.returncode,
|
|
146
|
+
"output": result.stdout.strip(),
|
|
147
|
+
"stderr": result.stderr.strip(),
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def ensure_expected_services(expected_services: Iterable[str]) -> dict[str, Any]:
|
|
152
|
+
"""
|
|
153
|
+
Ensure that a list of critical services is active, starting any that are stopped.
|
|
154
|
+
"""
|
|
155
|
+
result: dict[str, list[str]] = {"started": [], "already_running": [], "failed": []}
|
|
156
|
+
logger.info("Verifying expected services are running")
|
|
157
|
+
|
|
158
|
+
for svc_name in expected_services:
|
|
159
|
+
status = service_status(svc_name)
|
|
160
|
+
if status in ("active", "running"):
|
|
161
|
+
result["already_running"].append(svc_name)
|
|
162
|
+
elif status in ("inactive", "failed", "stopped"):
|
|
163
|
+
res = control_service(svc_name, "start")
|
|
164
|
+
if res.get("success"):
|
|
165
|
+
result["started"].append(svc_name)
|
|
166
|
+
else:
|
|
167
|
+
result["failed"].append(svc_name)
|
|
168
|
+
else:
|
|
169
|
+
result["failed"].append(svc_name)
|
|
170
|
+
|
|
171
|
+
return result
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# sysmaint/modules/startup.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
|
+
logger = logging.getLogger("sysmaint.startup")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def list_startup_items() -> list[dict[str, Any]]:
|
|
14
|
+
"""
|
|
15
|
+
List all configured startup applications and autoruns across Windows or Linux.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
List of startup program records with name, command, location, and impact.
|
|
19
|
+
"""
|
|
20
|
+
system = platform.system().lower()
|
|
21
|
+
logger.info("Enumerating startup applications on %s", system)
|
|
22
|
+
items: list[dict[str, Any]] = []
|
|
23
|
+
|
|
24
|
+
if system == "windows":
|
|
25
|
+
from ..utils import windows
|
|
26
|
+
raw_items = windows.get_windows_startup_items()
|
|
27
|
+
for it in raw_items:
|
|
28
|
+
cmd = it.get("command", "")
|
|
29
|
+
# Heuristic impact estimation
|
|
30
|
+
impact = "Medium"
|
|
31
|
+
cmd_lower = cmd.lower()
|
|
32
|
+
if any(k in cmd_lower for k in ("update", "helper", "tray", "sync", "notify")):
|
|
33
|
+
impact = "Low"
|
|
34
|
+
elif any(k in cmd_lower for k in ("steam", "epic", "discord", "electron", "teams", "slack", "chrome")):
|
|
35
|
+
impact = "High"
|
|
36
|
+
|
|
37
|
+
it["impact"] = impact
|
|
38
|
+
items.append(it)
|
|
39
|
+
return items
|
|
40
|
+
|
|
41
|
+
if system == "linux":
|
|
42
|
+
from ..utils import linux
|
|
43
|
+
raw_items = linux.get_linux_startup_items()
|
|
44
|
+
for it in raw_items:
|
|
45
|
+
it["impact"] = "Medium"
|
|
46
|
+
it["is_system"] = "/etc" in it.get("location", "")
|
|
47
|
+
items.append(it)
|
|
48
|
+
return items
|
|
49
|
+
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def toggle_startup_item(name: str, enable: bool) -> dict[str, Any]:
|
|
54
|
+
"""
|
|
55
|
+
Enable or disable a startup item.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
name: Name of the startup application.
|
|
59
|
+
enable: Whether to enable or disable the item.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
Dictionary indicating status.
|
|
63
|
+
"""
|
|
64
|
+
system = platform.system().lower()
|
|
65
|
+
logger.info("Setting startup item '%s' enabled=%s", name, enable)
|
|
66
|
+
|
|
67
|
+
if system == "windows":
|
|
68
|
+
try:
|
|
69
|
+
import winreg
|
|
70
|
+
# Check HKCU Run key
|
|
71
|
+
subkey = r"Software\Microsoft\Windows\CurrentVersion\Run"
|
|
72
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey, 0, winreg.KEY_ALL_ACCESS) as key:
|
|
73
|
+
if not enable:
|
|
74
|
+
try:
|
|
75
|
+
winreg.DeleteValue(key, name)
|
|
76
|
+
return {"success": True, "message": f"Removed '{name}' from HKCU Run key."}
|
|
77
|
+
except OSError:
|
|
78
|
+
pass
|
|
79
|
+
except Exception as exc:
|
|
80
|
+
return {"success": False, "error": str(exc)}
|
|
81
|
+
|
|
82
|
+
if system == "linux":
|
|
83
|
+
autostart_dir = Path.home() / ".config" / "autostart"
|
|
84
|
+
for f in autostart_dir.glob("*.desktop"):
|
|
85
|
+
if name.lower() in f.stem.lower():
|
|
86
|
+
try:
|
|
87
|
+
content = f.read_text(encoding="utf-8")
|
|
88
|
+
if f"Hidden={not enable}" not in content:
|
|
89
|
+
new_content = content + f"\nHidden={'true' if not enable else 'false'}\n"
|
|
90
|
+
f.write_text(new_content, encoding="utf-8")
|
|
91
|
+
return {"success": True, "message": f"Updated {f.name}"}
|
|
92
|
+
except Exception as exc:
|
|
93
|
+
return {"success": False, "error": str(exc)}
|
|
94
|
+
|
|
95
|
+
return {"success": False, "message": "Startup item not found or modification requires elevated privileges."}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# sysmaint/modules/sysinfo.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import logging
|
|
7
|
+
import platform
|
|
8
|
+
import time
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import psutil
|
|
12
|
+
|
|
13
|
+
from ..utils.common import format_bytes
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("sysmaint.sysinfo")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_cpu_info() -> dict[str, Any]:
|
|
19
|
+
"""
|
|
20
|
+
Get detailed processor metrics and model.
|
|
21
|
+
"""
|
|
22
|
+
cpu_freq = psutil.cpu_freq()
|
|
23
|
+
model = platform.processor() or "Generic CPU"
|
|
24
|
+
|
|
25
|
+
# On Windows, try querying wmic / registry for friendly CPU brand string
|
|
26
|
+
if platform.system().lower() == "windows":
|
|
27
|
+
try:
|
|
28
|
+
import winreg
|
|
29
|
+
key = winreg.OpenKey(
|
|
30
|
+
winreg.HKEY_LOCAL_MACHINE,
|
|
31
|
+
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
|
|
32
|
+
)
|
|
33
|
+
brand, _ = winreg.QueryValueEx(key, "ProcessorNameString")
|
|
34
|
+
if brand:
|
|
35
|
+
model = str(brand).strip()
|
|
36
|
+
except Exception:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
"model": model,
|
|
41
|
+
"physical_cores": psutil.cpu_count(logical=False) or 1,
|
|
42
|
+
"logical_cores": psutil.cpu_count(logical=True) or 1,
|
|
43
|
+
"current_frequency_mhz": round(cpu_freq.current, 1) if cpu_freq else None,
|
|
44
|
+
"max_frequency_mhz": round(cpu_freq.max, 1) if cpu_freq and cpu_freq.max else None,
|
|
45
|
+
"usage_percent": psutil.cpu_percent(interval=0.1),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def get_battery_info() -> dict[str, Any] | None:
|
|
50
|
+
"""
|
|
51
|
+
Get battery level and charging status if system has a battery.
|
|
52
|
+
"""
|
|
53
|
+
if hasattr(psutil, "sensors_battery"):
|
|
54
|
+
bat = psutil.sensors_battery()
|
|
55
|
+
if bat:
|
|
56
|
+
return {
|
|
57
|
+
"percent": bat.percent,
|
|
58
|
+
"power_plugged": bat.power_plugged,
|
|
59
|
+
"secs_left": bat.secsleft if bat.secsleft > 0 else None,
|
|
60
|
+
}
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_system_specs() -> dict[str, Any]:
|
|
65
|
+
"""
|
|
66
|
+
Collect complete system hardware specifications and OS information.
|
|
67
|
+
"""
|
|
68
|
+
logger.info("Collecting system hardware and OS specs")
|
|
69
|
+
boot_time_ts = psutil.boot_time()
|
|
70
|
+
boot_dt = datetime.datetime.fromtimestamp(boot_time_ts)
|
|
71
|
+
uptime_secs = int(time.time() - boot_time_ts)
|
|
72
|
+
|
|
73
|
+
uptime_hours = uptime_secs // 3600
|
|
74
|
+
uptime_mins = (uptime_secs % 3600) // 60
|
|
75
|
+
|
|
76
|
+
v_mem = psutil.virtual_memory()
|
|
77
|
+
|
|
78
|
+
# Calculate total disk capacity across physical partitions
|
|
79
|
+
total_disk_bytes = 0
|
|
80
|
+
used_disk_bytes = 0
|
|
81
|
+
for part in psutil.disk_partitions(all=False):
|
|
82
|
+
try:
|
|
83
|
+
u = psutil.disk_usage(part.mountpoint)
|
|
84
|
+
total_disk_bytes += u.total
|
|
85
|
+
used_disk_bytes += u.used
|
|
86
|
+
except (PermissionError, OSError):
|
|
87
|
+
continue
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
"os_name": platform.system(),
|
|
91
|
+
"os_version": platform.version(),
|
|
92
|
+
"os_release": platform.release(),
|
|
93
|
+
"architecture": platform.machine(),
|
|
94
|
+
"hostname": platform.node(),
|
|
95
|
+
"boot_time": boot_dt.strftime("%Y-%m-%d %H:%M:%S"),
|
|
96
|
+
"uptime_formatted": f"{uptime_hours}h {uptime_mins}m",
|
|
97
|
+
"uptime_seconds": uptime_secs,
|
|
98
|
+
"cpu": get_cpu_info(),
|
|
99
|
+
"memory": {
|
|
100
|
+
"total_bytes": v_mem.total,
|
|
101
|
+
"total_formatted": format_bytes(v_mem.total),
|
|
102
|
+
"available_formatted": format_bytes(v_mem.available),
|
|
103
|
+
"usage_percent": v_mem.percent,
|
|
104
|
+
},
|
|
105
|
+
"storage": {
|
|
106
|
+
"total_bytes": total_disk_bytes,
|
|
107
|
+
"total_formatted": format_bytes(total_disk_bytes),
|
|
108
|
+
"used_formatted": format_bytes(used_disk_bytes),
|
|
109
|
+
},
|
|
110
|
+
"battery": get_battery_info(),
|
|
111
|
+
"python_version": platform.python_version(),
|
|
112
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# src/sysmaint/service/server.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import platform
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from fastapi import FastAPI, Request
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
12
|
+
|
|
13
|
+
from .. import __brand__, __codename__, __version__
|
|
14
|
+
from ..config import SysMaintConfig, load_config
|
|
15
|
+
from ..modules import (
|
|
16
|
+
disk,
|
|
17
|
+
drivers,
|
|
18
|
+
integrity,
|
|
19
|
+
malware,
|
|
20
|
+
memory,
|
|
21
|
+
network,
|
|
22
|
+
optimizer,
|
|
23
|
+
recovery,
|
|
24
|
+
security,
|
|
25
|
+
services,
|
|
26
|
+
sysinfo,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_START_TIME = time.time()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DiagnoseRequest(BaseModel):
|
|
33
|
+
disk: bool = True
|
|
34
|
+
memory: bool = True
|
|
35
|
+
services: bool = False
|
|
36
|
+
drivers: bool = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ScanRequest(BaseModel):
|
|
40
|
+
yara: bool = True
|
|
41
|
+
clamav: bool = False
|
|
42
|
+
integrity: bool = True
|
|
43
|
+
offline: bool = True
|
|
44
|
+
target: str | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RepairRequest(BaseModel):
|
|
48
|
+
disk: bool = False
|
|
49
|
+
files: bool = False
|
|
50
|
+
services: bool = False
|
|
51
|
+
network: bool = False
|
|
52
|
+
offline_source: str | None = None
|
|
53
|
+
dry_run: bool = True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class TrashRestoreRequest(BaseModel):
|
|
57
|
+
name: str
|
|
58
|
+
destination: str | None = None
|
|
59
|
+
dry_run: bool = False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class CarveRequest(BaseModel):
|
|
63
|
+
source_path: str
|
|
64
|
+
output_dir: str
|
|
65
|
+
file_types: list[str] | None = None
|
|
66
|
+
max_files: int = Field(default=50, ge=1, le=500)
|
|
67
|
+
dry_run: bool = True
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def create_app(config: SysMaintConfig | None = None) -> FastAPI:
|
|
71
|
+
"""Create the SysMaint Sentinel FastAPI microservice."""
|
|
72
|
+
cfg = config or load_config()
|
|
73
|
+
app = FastAPI(
|
|
74
|
+
title="SysMaint Sentinel Microservice",
|
|
75
|
+
description=(
|
|
76
|
+
f"Cross-Platform System Maintenance, Security & Data Recovery API "
|
|
77
|
+
f"by {__brand__}."
|
|
78
|
+
),
|
|
79
|
+
version=__version__,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
@app.middleware("http")
|
|
83
|
+
async def add_brand_header(request: Request, call_next: Any):
|
|
84
|
+
response = await call_next(request)
|
|
85
|
+
response.headers["X-Powered-By"] = __brand__
|
|
86
|
+
response.headers["X-Service-Version"] = __version__
|
|
87
|
+
return response
|
|
88
|
+
|
|
89
|
+
@app.get("/health")
|
|
90
|
+
def health() -> dict[str, Any]:
|
|
91
|
+
return {
|
|
92
|
+
"status": "ok",
|
|
93
|
+
"service": "sysmaint",
|
|
94
|
+
"codename": __codename__,
|
|
95
|
+
"version": __version__,
|
|
96
|
+
"brand": __brand__,
|
|
97
|
+
"platform": platform.system(),
|
|
98
|
+
"uptime_seconds": round(time.time() - _START_TIME, 2),
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
@app.get("/v1/sysinfo")
|
|
102
|
+
def get_sysinfo() -> dict[str, Any]:
|
|
103
|
+
return {"sysinfo": sysinfo.get_system_specs()}
|
|
104
|
+
|
|
105
|
+
@app.get("/v1/smart-scan")
|
|
106
|
+
def get_smart_scan() -> dict[str, Any]:
|
|
107
|
+
return {"smart_scan": optimizer.run_smart_scan(cfg)}
|
|
108
|
+
|
|
109
|
+
@app.get("/v1/security")
|
|
110
|
+
def get_security() -> dict[str, Any]:
|
|
111
|
+
return {"security": security.audit_security_posture()}
|
|
112
|
+
|
|
113
|
+
@app.post("/v1/diagnose")
|
|
114
|
+
def run_diagnose(req: DiagnoseRequest) -> dict[str, Any]:
|
|
115
|
+
out: dict[str, Any] = {}
|
|
116
|
+
if req.disk:
|
|
117
|
+
out["disk"] = disk.check_disk(repair=False)
|
|
118
|
+
if req.memory:
|
|
119
|
+
out["memory"] = memory.check_memory()
|
|
120
|
+
if req.services:
|
|
121
|
+
out["services"] = services.list_services()
|
|
122
|
+
if req.drivers:
|
|
123
|
+
out["drivers"] = drivers.check_drivers()
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
@app.post("/v1/scan")
|
|
127
|
+
def run_scan(req: ScanRequest) -> dict[str, Any]:
|
|
128
|
+
out: dict[str, Any] = {}
|
|
129
|
+
if req.integrity:
|
|
130
|
+
out["integrity"] = integrity.check_integrity(repair=False)
|
|
131
|
+
if req.yara or req.clamav:
|
|
132
|
+
mal_cfg = malware.MalwareConfig(
|
|
133
|
+
use_clamav=req.clamav,
|
|
134
|
+
use_yara=req.yara,
|
|
135
|
+
yara_rules_path=cfg.malware.yara_rules_path,
|
|
136
|
+
use_virustotal=False,
|
|
137
|
+
vt_api_key="",
|
|
138
|
+
)
|
|
139
|
+
out["malware"] = malware.scan(
|
|
140
|
+
mal_cfg,
|
|
141
|
+
target=Path(req.target) if req.target else None,
|
|
142
|
+
offline=req.offline,
|
|
143
|
+
quick_scan=req.target is None,
|
|
144
|
+
)
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
@app.post("/v1/repair")
|
|
148
|
+
def run_repair(req: RepairRequest) -> dict[str, Any]:
|
|
149
|
+
out: dict[str, Any] = {"dry_run": req.dry_run}
|
|
150
|
+
if req.disk:
|
|
151
|
+
out["disk"] = (
|
|
152
|
+
{"dry_run": "chkdsk /f or fsck -y"}
|
|
153
|
+
if req.dry_run
|
|
154
|
+
else disk.check_disk(repair=True)
|
|
155
|
+
)
|
|
156
|
+
if req.files:
|
|
157
|
+
out["integrity"] = (
|
|
158
|
+
{"dry_run": "DISM /RestoreHealth and SFC /scannow"}
|
|
159
|
+
if req.dry_run
|
|
160
|
+
else integrity.check_integrity(repair=True, offline_source=req.offline_source)
|
|
161
|
+
)
|
|
162
|
+
if req.services:
|
|
163
|
+
out["services"] = (
|
|
164
|
+
{"dry_run": "ensure expected services"}
|
|
165
|
+
if req.dry_run
|
|
166
|
+
else services.ensure_expected_services(cfg.services.expected_services)
|
|
167
|
+
)
|
|
168
|
+
if req.network:
|
|
169
|
+
out["network"] = network.reset_network_stack(dry_run=req.dry_run)
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
@app.get("/v1/recovery/trash")
|
|
173
|
+
def api_list_trash(limit: int = 50) -> dict[str, Any]:
|
|
174
|
+
return recovery.list_trash_items(limit=limit)
|
|
175
|
+
|
|
176
|
+
@app.post("/v1/recovery/trash/restore")
|
|
177
|
+
def api_restore_trash(req: TrashRestoreRequest) -> dict[str, Any]:
|
|
178
|
+
return recovery.restore_trash_item(
|
|
179
|
+
name=req.name,
|
|
180
|
+
destination=Path(req.destination) if req.destination else None,
|
|
181
|
+
dry_run=req.dry_run,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
@app.get("/v1/recovery/shadows")
|
|
185
|
+
def api_list_shadows() -> dict[str, Any]:
|
|
186
|
+
return recovery.list_shadow_copies()
|
|
187
|
+
|
|
188
|
+
@app.get("/v1/recovery/temp")
|
|
189
|
+
def api_scan_temp(limit: int = 50) -> dict[str, Any]:
|
|
190
|
+
return recovery.scan_recoverable_temp_files(limit=limit)
|
|
191
|
+
|
|
192
|
+
@app.post("/v1/recovery/carve")
|
|
193
|
+
def api_carve(req: CarveRequest) -> dict[str, Any]:
|
|
194
|
+
return recovery.carve_recoverable_files(
|
|
195
|
+
source_path=Path(req.source_path),
|
|
196
|
+
output_dir=Path(req.output_dir),
|
|
197
|
+
file_types=req.file_types,
|
|
198
|
+
max_files=req.max_files,
|
|
199
|
+
dry_run=req.dry_run,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
return app
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def run_server(host: str = "127.0.0.1", port: int = 8765) -> None:
|
|
206
|
+
"""Launch the SysMaint microservice with Uvicorn."""
|
|
207
|
+
import uvicorn
|
|
208
|
+
|
|
209
|
+
app = create_app()
|
|
210
|
+
uvicorn.run(app, host=host, port=port, log_level="info")
|