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,249 @@
|
|
|
1
|
+
# sysmaint/modules/cleaner.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from ..utils.common import format_bytes, safe_delete_dir_contents
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("sysmaint.cleaner")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_junk_targets() -> dict[str, list[Path]]:
|
|
17
|
+
"""
|
|
18
|
+
Locate junk file target paths grouped by category based on current OS.
|
|
19
|
+
"""
|
|
20
|
+
system = platform.system().lower()
|
|
21
|
+
targets: dict[str, list[Path]] = {
|
|
22
|
+
"user_temp": [],
|
|
23
|
+
"system_temp": [],
|
|
24
|
+
"browser_cache": [],
|
|
25
|
+
"system_logs": [],
|
|
26
|
+
"package_cache": [],
|
|
27
|
+
"thumbnails": [],
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
user_home = Path.home()
|
|
31
|
+
|
|
32
|
+
if system == "windows":
|
|
33
|
+
# 1. User Temp
|
|
34
|
+
user_temp = os.environ.get("TEMP") or os.environ.get("TMP")
|
|
35
|
+
if user_temp and Path(user_temp).is_dir():
|
|
36
|
+
targets["user_temp"].append(Path(user_temp))
|
|
37
|
+
|
|
38
|
+
# 2. System Temp & Prefetch
|
|
39
|
+
sys_temp = Path(r"C:\Windows\Temp")
|
|
40
|
+
if sys_temp.is_dir():
|
|
41
|
+
targets["system_temp"].append(sys_temp)
|
|
42
|
+
prefetch = Path(r"C:\Windows\Prefetch")
|
|
43
|
+
if prefetch.is_dir():
|
|
44
|
+
targets["system_temp"].append(prefetch)
|
|
45
|
+
|
|
46
|
+
# 3. Browser Caches (Chrome, Edge, Brave, Firefox)
|
|
47
|
+
local_app_data = os.environ.get("LOCALAPPDATA")
|
|
48
|
+
app_data = os.environ.get("APPDATA")
|
|
49
|
+
|
|
50
|
+
if local_app_data:
|
|
51
|
+
lad = Path(local_app_data)
|
|
52
|
+
# Chrome Cache
|
|
53
|
+
chrome_cache = lad / r"Google\Chrome\User Data\Default\Cache"
|
|
54
|
+
if chrome_cache.is_dir():
|
|
55
|
+
targets["browser_cache"].append(chrome_cache)
|
|
56
|
+
# Edge Cache
|
|
57
|
+
edge_cache = lad / r"Microsoft\Edge\User Data\Default\Cache"
|
|
58
|
+
if edge_cache.is_dir():
|
|
59
|
+
targets["browser_cache"].append(edge_cache)
|
|
60
|
+
# Brave Cache
|
|
61
|
+
brave_cache = lad / r"BraveSoftware\Brave-Browser\User Data\Default\Cache"
|
|
62
|
+
if brave_cache.is_dir():
|
|
63
|
+
targets["browser_cache"].append(brave_cache)
|
|
64
|
+
# Crash Dumps
|
|
65
|
+
crash_dumps = lad / "CrashDumps"
|
|
66
|
+
if crash_dumps.is_dir():
|
|
67
|
+
targets["system_logs"].append(crash_dumps)
|
|
68
|
+
# Windows Explorer Thumbnails
|
|
69
|
+
thumb_cache = lad / r"Microsoft\Windows\Explorer"
|
|
70
|
+
if thumb_cache.is_dir():
|
|
71
|
+
targets["thumbnails"].append(thumb_cache)
|
|
72
|
+
|
|
73
|
+
if app_data:
|
|
74
|
+
mozilla = Path(app_data) / r"Mozilla\Firefox\Profiles"
|
|
75
|
+
if mozilla.is_dir():
|
|
76
|
+
for p in mozilla.iterdir():
|
|
77
|
+
if (p / "cache2").is_dir():
|
|
78
|
+
targets["browser_cache"].append(p / "cache2")
|
|
79
|
+
|
|
80
|
+
# 4. Windows Update Download Cache
|
|
81
|
+
soft_dist = Path(r"C:\Windows\SoftwareDistribution\Download")
|
|
82
|
+
if soft_dist.is_dir():
|
|
83
|
+
targets["package_cache"].append(soft_dist)
|
|
84
|
+
|
|
85
|
+
elif system == "linux":
|
|
86
|
+
# 1. User Temp
|
|
87
|
+
targets["user_temp"].append(Path("/tmp"))
|
|
88
|
+
targets["user_temp"].append(Path("/var/tmp"))
|
|
89
|
+
|
|
90
|
+
# 2. User Cache
|
|
91
|
+
user_cache = user_home / ".cache"
|
|
92
|
+
if user_cache.is_dir():
|
|
93
|
+
targets["user_temp"].append(user_cache)
|
|
94
|
+
# Browser caches inside .cache
|
|
95
|
+
for b in ("google-chrome", "chromium", "mozilla/firefox", "BraveSoftware"):
|
|
96
|
+
b_path = user_cache / b
|
|
97
|
+
if b_path.is_dir():
|
|
98
|
+
targets["browser_cache"].append(b_path)
|
|
99
|
+
# Thumbnails
|
|
100
|
+
thumbs = user_cache / "thumbnails"
|
|
101
|
+
if thumbs.is_dir():
|
|
102
|
+
targets["thumbnails"].append(thumbs)
|
|
103
|
+
|
|
104
|
+
# 3. System Logs
|
|
105
|
+
var_log = Path("/var/log")
|
|
106
|
+
if var_log.is_dir():
|
|
107
|
+
targets["system_logs"].append(var_log)
|
|
108
|
+
|
|
109
|
+
return targets
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def calculate_dir_size(dir_path: Path) -> tuple[int, int]:
|
|
113
|
+
"""
|
|
114
|
+
Calculate total bytes and file count inside a directory safely without following symlinks outside.
|
|
115
|
+
"""
|
|
116
|
+
if not dir_path.is_dir():
|
|
117
|
+
return 0, 0
|
|
118
|
+
|
|
119
|
+
total_size = 0
|
|
120
|
+
file_count = 0
|
|
121
|
+
try:
|
|
122
|
+
for entry in dir_path.rglob("*"):
|
|
123
|
+
try:
|
|
124
|
+
if entry.is_file():
|
|
125
|
+
total_size += entry.stat().st_size
|
|
126
|
+
file_count += 1
|
|
127
|
+
except (PermissionError, OSError):
|
|
128
|
+
continue
|
|
129
|
+
except (PermissionError, OSError):
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
return total_size, file_count
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def scan_junk(categories: list[str] | None = None) -> dict[str, Any]:
|
|
136
|
+
"""
|
|
137
|
+
Scan system for junk, temporary files, and caches without deleting anything.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
categories: Optional subset of categories to scan.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
Itemized summary of reclaimable storage space.
|
|
144
|
+
"""
|
|
145
|
+
logger.info("Scanning for junk and temporary files")
|
|
146
|
+
all_targets = get_junk_targets()
|
|
147
|
+
selected_cats = categories or list(all_targets.keys())
|
|
148
|
+
|
|
149
|
+
breakdown: dict[str, dict[str, Any]] = {}
|
|
150
|
+
total_bytes = 0
|
|
151
|
+
total_files = 0
|
|
152
|
+
|
|
153
|
+
for cat, paths in all_targets.items():
|
|
154
|
+
if cat not in selected_cats:
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
cat_bytes = 0
|
|
158
|
+
cat_files = 0
|
|
159
|
+
found_paths = []
|
|
160
|
+
|
|
161
|
+
for p in paths:
|
|
162
|
+
if p.exists():
|
|
163
|
+
b_size, f_count = calculate_dir_size(p)
|
|
164
|
+
cat_bytes += b_size
|
|
165
|
+
cat_files += f_count
|
|
166
|
+
found_paths.append(str(p))
|
|
167
|
+
|
|
168
|
+
breakdown[cat] = {
|
|
169
|
+
"bytes": cat_bytes,
|
|
170
|
+
"bytes_formatted": format_bytes(cat_bytes),
|
|
171
|
+
"files_count": cat_files,
|
|
172
|
+
"paths": found_paths,
|
|
173
|
+
}
|
|
174
|
+
total_bytes += cat_bytes
|
|
175
|
+
total_files += cat_files
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
"total_bytes": total_bytes,
|
|
179
|
+
"total_bytes_formatted": format_bytes(total_bytes),
|
|
180
|
+
"total_files": total_files,
|
|
181
|
+
"categories": breakdown,
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def clean_junk(
|
|
186
|
+
categories: list[str] | None = None,
|
|
187
|
+
dry_run: bool = False,
|
|
188
|
+
) -> dict[str, Any]:
|
|
189
|
+
"""
|
|
190
|
+
Safely clean junk files and caches from selected categories.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
categories: Categories to clean. Defaults to all safe categories.
|
|
194
|
+
dry_run: If True, only simulates the cleanup.
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
Dictionary with cleaned bytes, deleted file count, and category results.
|
|
198
|
+
"""
|
|
199
|
+
logger.info("Starting junk cleaning (dry_run=%s)", dry_run)
|
|
200
|
+
if dry_run:
|
|
201
|
+
scan_res = scan_junk(categories)
|
|
202
|
+
return {
|
|
203
|
+
"dry_run": True,
|
|
204
|
+
"freed_bytes": scan_res["total_bytes"],
|
|
205
|
+
"freed_bytes_formatted": scan_res["total_bytes_formatted"],
|
|
206
|
+
"deleted_files": scan_res["total_files"],
|
|
207
|
+
"categories": scan_res["categories"],
|
|
208
|
+
"message": f"Dry-run: Would free {scan_res['total_bytes_formatted']} across {scan_res['total_files']} files.",
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
all_targets = get_junk_targets()
|
|
212
|
+
selected_cats = categories or list(all_targets.keys())
|
|
213
|
+
|
|
214
|
+
total_freed = 0
|
|
215
|
+
total_deleted = 0
|
|
216
|
+
results: dict[str, dict[str, Any]] = {}
|
|
217
|
+
|
|
218
|
+
for cat in selected_cats:
|
|
219
|
+
paths = all_targets.get(cat, [])
|
|
220
|
+
cat_freed = 0
|
|
221
|
+
cat_deleted = 0
|
|
222
|
+
|
|
223
|
+
for p in paths:
|
|
224
|
+
if p.is_dir():
|
|
225
|
+
f_count, b_freed = safe_delete_dir_contents(p)
|
|
226
|
+
cat_deleted += f_count
|
|
227
|
+
cat_freed += b_freed
|
|
228
|
+
|
|
229
|
+
results[cat] = {
|
|
230
|
+
"freed_bytes": cat_freed,
|
|
231
|
+
"freed_bytes_formatted": format_bytes(cat_freed),
|
|
232
|
+
"deleted_files": cat_deleted,
|
|
233
|
+
}
|
|
234
|
+
total_freed += cat_freed
|
|
235
|
+
total_deleted += cat_deleted
|
|
236
|
+
|
|
237
|
+
# Run Linux package clean if applicable
|
|
238
|
+
if platform.system().lower() == "linux" and "package_cache" in selected_cats:
|
|
239
|
+
from ..utils.linux import clean_package_cache
|
|
240
|
+
clean_package_cache(dry_run=False)
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
"dry_run": False,
|
|
244
|
+
"freed_bytes": total_freed,
|
|
245
|
+
"freed_bytes_formatted": format_bytes(total_freed),
|
|
246
|
+
"deleted_files": total_deleted,
|
|
247
|
+
"categories": results,
|
|
248
|
+
"message": f"Cleaned {format_bytes(total_freed)} of junk files ({total_deleted} files removed).",
|
|
249
|
+
}
|
sysmaint/modules/disk.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# sysmaint/modules/disk.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import platform
|
|
7
|
+
import shutil
|
|
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_fsck_output
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("sysmaint.disk")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_disk_partitions() -> list[dict[str, Any]]:
|
|
19
|
+
"""
|
|
20
|
+
Return all mounted partitions with storage metrics (total, used, free, percent).
|
|
21
|
+
"""
|
|
22
|
+
partitions_info = []
|
|
23
|
+
for part in psutil.disk_partitions(all=False):
|
|
24
|
+
try:
|
|
25
|
+
usage = psutil.disk_usage(part.mountpoint)
|
|
26
|
+
partitions_info.append({
|
|
27
|
+
"device": part.device,
|
|
28
|
+
"mountpoint": part.mountpoint,
|
|
29
|
+
"fstype": part.fstype,
|
|
30
|
+
"opts": part.opts,
|
|
31
|
+
"total": usage.total,
|
|
32
|
+
"used": usage.used,
|
|
33
|
+
"free": usage.free,
|
|
34
|
+
"percent": usage.percent,
|
|
35
|
+
"total_formatted": format_bytes(usage.total),
|
|
36
|
+
"used_formatted": format_bytes(usage.used),
|
|
37
|
+
"free_formatted": format_bytes(usage.free),
|
|
38
|
+
})
|
|
39
|
+
except (PermissionError, OSError):
|
|
40
|
+
continue
|
|
41
|
+
return partitions_info
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def check_smart_health() -> list[dict[str, Any]]:
|
|
45
|
+
"""
|
|
46
|
+
Check S.M.A.R.T. disk health status using smartctl or OS-specific tools.
|
|
47
|
+
"""
|
|
48
|
+
system = platform.system().lower()
|
|
49
|
+
drives: list[dict[str, Any]] = []
|
|
50
|
+
|
|
51
|
+
# Check smartctl if installed
|
|
52
|
+
if shutil.which("smartctl"):
|
|
53
|
+
res = run_command(["smartctl", "--scan"], check=False)
|
|
54
|
+
for line in res.stdout.splitlines():
|
|
55
|
+
parts = line.split(None, 2)
|
|
56
|
+
if parts and parts[0].startswith("/dev/"):
|
|
57
|
+
dev_path = parts[0]
|
|
58
|
+
health_res = run_command(["smartctl", "-H", dev_path], check=False)
|
|
59
|
+
passed = "PASSED" in health_res.stdout or "OK" in health_res.stdout
|
|
60
|
+
drives.append({
|
|
61
|
+
"device": dev_path,
|
|
62
|
+
"type": parts[1] if len(parts) > 1 else "Unknown",
|
|
63
|
+
"smart_status": "PASSED" if passed else "WARNING/FAILED",
|
|
64
|
+
"healthy": passed,
|
|
65
|
+
})
|
|
66
|
+
if drives:
|
|
67
|
+
return drives
|
|
68
|
+
|
|
69
|
+
if system == "windows":
|
|
70
|
+
from ..utils.windows import run_powershell
|
|
71
|
+
script = (
|
|
72
|
+
"Get-PhysicalDisk -ErrorAction SilentlyContinue | "
|
|
73
|
+
"Select-Object DeviceId, FriendlyName, MediaType, OperationalStatus, HealthStatus, Size | "
|
|
74
|
+
"ConvertTo-Json"
|
|
75
|
+
)
|
|
76
|
+
data = run_powershell(script, as_json=True)
|
|
77
|
+
if isinstance(data, list):
|
|
78
|
+
for disk in data:
|
|
79
|
+
if isinstance(disk, dict):
|
|
80
|
+
drives.append({
|
|
81
|
+
"device": f"Disk {disk.get('DeviceId', '')}",
|
|
82
|
+
"name": disk.get("FriendlyName", "Physical Disk"),
|
|
83
|
+
"media_type": disk.get("MediaType", "Unspecified"),
|
|
84
|
+
"smart_status": disk.get("HealthStatus", "Healthy"),
|
|
85
|
+
"operational_status": disk.get("OperationalStatus", "OK"),
|
|
86
|
+
"size_formatted": format_bytes(disk.get("Size", 0)),
|
|
87
|
+
"healthy": disk.get("HealthStatus") in ("Healthy", None),
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
return drives
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def check_disk(repair: bool = False, volume: str | None = None) -> dict[str, Any]:
|
|
94
|
+
"""
|
|
95
|
+
Check disk/filesystem health and partition statistics.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
repair: If True, attempt to repair filesystem errors.
|
|
99
|
+
volume: Optional Windows volume letter (e.g., 'C:') or Linux mountpoint.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Dictionary with partitions, tool results, and health status.
|
|
103
|
+
"""
|
|
104
|
+
system = platform.system().lower()
|
|
105
|
+
partitions = get_disk_partitions()
|
|
106
|
+
smart_info = check_smart_health()
|
|
107
|
+
|
|
108
|
+
logger.info("Running disk check (system=%s, repair=%s)", system, repair)
|
|
109
|
+
|
|
110
|
+
if system == "windows":
|
|
111
|
+
target_volume = volume or "C:"
|
|
112
|
+
if not target_volume.endswith(":"):
|
|
113
|
+
target_volume = f"{target_volume}:"
|
|
114
|
+
|
|
115
|
+
cmd = ["chkdsk", target_volume]
|
|
116
|
+
if repair:
|
|
117
|
+
cmd.append("/f")
|
|
118
|
+
else:
|
|
119
|
+
cmd.append("/scan")
|
|
120
|
+
|
|
121
|
+
result = run_command(cmd, check=False)
|
|
122
|
+
return {
|
|
123
|
+
"tool": "chkdsk",
|
|
124
|
+
"volume": target_volume,
|
|
125
|
+
"repair": repair,
|
|
126
|
+
"returncode": result.returncode,
|
|
127
|
+
"output": result.stdout,
|
|
128
|
+
"stderr": result.stderr,
|
|
129
|
+
"partitions": partitions,
|
|
130
|
+
"smart_drives": smart_info,
|
|
131
|
+
"healthy": result.returncode == 0,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if system == "linux":
|
|
135
|
+
cmd = ["fsck"]
|
|
136
|
+
if repair:
|
|
137
|
+
cmd.append("-y")
|
|
138
|
+
else:
|
|
139
|
+
cmd.append("-N")
|
|
140
|
+
cmd.append("-A")
|
|
141
|
+
|
|
142
|
+
result = run_command(cmd, check=False)
|
|
143
|
+
parsed = parse_fsck_output(result.stdout)
|
|
144
|
+
return {
|
|
145
|
+
"tool": "fsck",
|
|
146
|
+
"repair": repair,
|
|
147
|
+
"returncode": result.returncode,
|
|
148
|
+
"output": result.stdout,
|
|
149
|
+
"stderr": result.stderr,
|
|
150
|
+
"parsed": parsed,
|
|
151
|
+
"partitions": partitions,
|
|
152
|
+
"smart_drives": smart_info,
|
|
153
|
+
"healthy": result.returncode in (0, 1),
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
"partitions": partitions,
|
|
158
|
+
"smart_drives": smart_info,
|
|
159
|
+
"healthy": True,
|
|
160
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# sysmaint/modules/drivers.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.common import run_command
|
|
11
|
+
from ..utils.parsers import parse_driverquery_output
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("sysmaint.drivers")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check_drivers() -> dict[str, Any]:
|
|
17
|
+
"""
|
|
18
|
+
List installed drivers / kernel modules and detect hardware device issues.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
Dictionary with driver list, device errors, and overall driver health status.
|
|
22
|
+
"""
|
|
23
|
+
system = platform.system().lower()
|
|
24
|
+
logger.info("Enumerating drivers and hardware devices for %s", system)
|
|
25
|
+
|
|
26
|
+
drivers: list[dict[str, Any]] = []
|
|
27
|
+
faulty_devices: list[dict[str, Any]] = []
|
|
28
|
+
|
|
29
|
+
if system == "windows":
|
|
30
|
+
from ..utils.windows import get_pnp_device_errors
|
|
31
|
+
|
|
32
|
+
# Check driver query
|
|
33
|
+
res = run_command(["driverquery", "/v", "/fo", "csv"], check=False)
|
|
34
|
+
if res.returncode == 0:
|
|
35
|
+
drivers = parse_driverquery_output(res.stdout)
|
|
36
|
+
else:
|
|
37
|
+
# Fallback to non-csv
|
|
38
|
+
res_txt = run_command(["driverquery"], check=False)
|
|
39
|
+
drivers = parse_driverquery_output(res_txt.stdout)
|
|
40
|
+
|
|
41
|
+
# Detect faulty devices
|
|
42
|
+
try:
|
|
43
|
+
faulty_devices = get_pnp_device_errors()
|
|
44
|
+
except Exception as exc:
|
|
45
|
+
logger.debug("Failed to query PnP devices: %s", exc)
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
"tool": "driverquery / PnP",
|
|
49
|
+
"drivers_count": len(drivers),
|
|
50
|
+
"drivers": drivers[:100], # cap at 100 for telemetry
|
|
51
|
+
"faulty_devices": faulty_devices,
|
|
52
|
+
"healthy": len(faulty_devices) == 0,
|
|
53
|
+
"status": "Healthy" if not faulty_devices else f"Found {len(faulty_devices)} problematic device(s)",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if system == "linux":
|
|
57
|
+
res = run_command(["lsmod"], check=False)
|
|
58
|
+
if res.returncode == 0:
|
|
59
|
+
for line in res.stdout.splitlines()[1:]:
|
|
60
|
+
parts = line.split()
|
|
61
|
+
if len(parts) >= 3:
|
|
62
|
+
drivers.append({
|
|
63
|
+
"name": parts[0],
|
|
64
|
+
"size": parts[1],
|
|
65
|
+
"used_by_count": parts[2],
|
|
66
|
+
"used_by": parts[3] if len(parts) > 3 else "",
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
# Check PCI devices
|
|
70
|
+
if shutil.which("lspci"):
|
|
71
|
+
pci_res = run_command(["lspci"], check=False)
|
|
72
|
+
pci_devices = [line.strip() for line in pci_res.stdout.splitlines() if line.strip()]
|
|
73
|
+
else:
|
|
74
|
+
pci_devices = []
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
"tool": "lsmod",
|
|
78
|
+
"modules_count": len(drivers),
|
|
79
|
+
"drivers": drivers[:100],
|
|
80
|
+
"pci_devices": pci_devices[:50],
|
|
81
|
+
"faulty_devices": [],
|
|
82
|
+
"healthy": True,
|
|
83
|
+
"status": "Healthy",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
"error": f"Unsupported platform: {system}",
|
|
88
|
+
"healthy": True,
|
|
89
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# sysmaint/modules/integrity.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import platform
|
|
7
|
+
import shutil
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from ..utils.common import run_command, stream_command
|
|
12
|
+
from ..utils.parsers import parse_dism_output, parse_sfc_output
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("sysmaint.integrity")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def check_integrity(
|
|
18
|
+
repair: bool = False,
|
|
19
|
+
offline_source: str | None = None,
|
|
20
|
+
progress_cb: Callable[[str, float | None], None] | None = None,
|
|
21
|
+
) -> dict[str, Any]:
|
|
22
|
+
"""
|
|
23
|
+
Verify system file and package integrity.
|
|
24
|
+
|
|
25
|
+
Windows: DISM (CheckHealth/ScanHealth or RestoreHealth) + SFC (verifyonly or scannow).
|
|
26
|
+
Linux: dpkg/rpm/pacman verification and systemd journal verification.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
repair: If True, run repair commands; otherwise run read-only checks.
|
|
30
|
+
offline_source: Optional local WIM/ESD source path for offline DISM repair.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Dictionary keyed by tool with parsed status, output, and health summary.
|
|
34
|
+
"""
|
|
35
|
+
system = platform.system().lower()
|
|
36
|
+
logger.info("Running system integrity check (system=%s, repair=%s)", system, repair)
|
|
37
|
+
|
|
38
|
+
if system == "windows":
|
|
39
|
+
results: dict[str, Any] = {}
|
|
40
|
+
|
|
41
|
+
# 1. DISM
|
|
42
|
+
if repair:
|
|
43
|
+
dism_cmd = ["Dism.exe", "/Online", "/Cleanup-Image", "/RestoreHealth"]
|
|
44
|
+
if offline_source:
|
|
45
|
+
dism_cmd.extend([f"/Source:{offline_source}", "/LimitAccess"])
|
|
46
|
+
else:
|
|
47
|
+
dism_cmd = ["Dism.exe", "/Online", "/Cleanup-Image", "/ScanHealth"]
|
|
48
|
+
|
|
49
|
+
if progress_cb:
|
|
50
|
+
progress_cb("Starting Windows DISM health check...", None)
|
|
51
|
+
dism_result = stream_command(dism_cmd, on_line=progress_cb)
|
|
52
|
+
else:
|
|
53
|
+
dism_result = run_command(dism_cmd, check=False)
|
|
54
|
+
parsed_dism = parse_dism_output(dism_result.stdout)
|
|
55
|
+
results["dism"] = {
|
|
56
|
+
"returncode": dism_result.returncode,
|
|
57
|
+
"parsed": parsed_dism,
|
|
58
|
+
"output": dism_result.stdout,
|
|
59
|
+
"stderr": dism_result.stderr,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
# 2. SFC
|
|
63
|
+
if repair:
|
|
64
|
+
sfc_cmd = ["sfc", "/scannow"]
|
|
65
|
+
else:
|
|
66
|
+
sfc_cmd = ["sfc", "/verifyonly"]
|
|
67
|
+
|
|
68
|
+
if progress_cb:
|
|
69
|
+
progress_cb("Starting Windows System File Checker (SFC)...", None)
|
|
70
|
+
sfc_result = stream_command(sfc_cmd, on_line=progress_cb)
|
|
71
|
+
else:
|
|
72
|
+
sfc_result = run_command(sfc_cmd, check=False)
|
|
73
|
+
parsed_sfc = parse_sfc_output(sfc_result.stdout)
|
|
74
|
+
results["sfc"] = {
|
|
75
|
+
"returncode": sfc_result.returncode,
|
|
76
|
+
"parsed": parsed_sfc,
|
|
77
|
+
"output": sfc_result.stdout,
|
|
78
|
+
"stderr": sfc_result.stderr,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
overall_healthy = (
|
|
82
|
+
dism_result.returncode == 0
|
|
83
|
+
and sfc_result.returncode in (0, 1)
|
|
84
|
+
and not parsed_sfc.get("corruptions_found", False)
|
|
85
|
+
)
|
|
86
|
+
if repair and parsed_sfc.get("repaired", False):
|
|
87
|
+
overall_healthy = True
|
|
88
|
+
|
|
89
|
+
results["healthy"] = overall_healthy
|
|
90
|
+
results["status"] = "Clean" if overall_healthy else "Corruption Detected"
|
|
91
|
+
return results
|
|
92
|
+
|
|
93
|
+
if system == "linux":
|
|
94
|
+
results = {}
|
|
95
|
+
pm = None
|
|
96
|
+
for candidate in ("dpkg", "rpm", "pacman"):
|
|
97
|
+
if shutil.which(candidate):
|
|
98
|
+
pm = candidate
|
|
99
|
+
break
|
|
100
|
+
|
|
101
|
+
if pm == "dpkg":
|
|
102
|
+
result = run_command(["dpkg", "--verify"], check=False)
|
|
103
|
+
results["package_manager"] = {
|
|
104
|
+
"tool": "dpkg",
|
|
105
|
+
"returncode": result.returncode,
|
|
106
|
+
"corrupted_files_count": len(result.stdout.splitlines()),
|
|
107
|
+
"output": result.stdout[:2000],
|
|
108
|
+
"healthy": result.returncode == 0,
|
|
109
|
+
}
|
|
110
|
+
elif pm == "rpm":
|
|
111
|
+
result = run_command(["rpm", "-Va"], check=False)
|
|
112
|
+
results["package_manager"] = {
|
|
113
|
+
"tool": "rpm",
|
|
114
|
+
"returncode": result.returncode,
|
|
115
|
+
"corrupted_files_count": len(result.stdout.splitlines()),
|
|
116
|
+
"output": result.stdout[:2000],
|
|
117
|
+
"healthy": result.returncode == 0,
|
|
118
|
+
}
|
|
119
|
+
elif pm == "pacman":
|
|
120
|
+
result = run_command(["pacman", "-Qk"], check=False)
|
|
121
|
+
results["package_manager"] = {
|
|
122
|
+
"tool": "pacman",
|
|
123
|
+
"returncode": result.returncode,
|
|
124
|
+
"output": result.stdout[:2000],
|
|
125
|
+
"healthy": result.returncode == 0,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
# Verify systemd journal if available
|
|
129
|
+
if shutil.which("journalctl"):
|
|
130
|
+
journal_result = run_command(["journalctl", "--verify"], check=False)
|
|
131
|
+
results["journalctl"] = {
|
|
132
|
+
"returncode": journal_result.returncode,
|
|
133
|
+
"healthy": journal_result.returncode == 0,
|
|
134
|
+
"output": journal_result.stdout,
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
overall_healthy = all(
|
|
138
|
+
v.get("healthy", True) for v in results.values() if isinstance(v, dict)
|
|
139
|
+
)
|
|
140
|
+
results["healthy"] = overall_healthy
|
|
141
|
+
results["status"] = "Clean" if overall_healthy else "Integrity Issues Found"
|
|
142
|
+
return results
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
"error": f"Unsupported platform: {system}",
|
|
146
|
+
"healthy": True,
|
|
147
|
+
"status": "Unknown",
|
|
148
|
+
}
|