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
sysmaint/tui/modals.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# src/sysmaint/tui/modals.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, ClassVar
|
|
7
|
+
|
|
8
|
+
from rich.json import JSON as RichJSON
|
|
9
|
+
from rich.panel import Panel
|
|
10
|
+
from textual.app import ComposeResult
|
|
11
|
+
from textual.binding import Binding
|
|
12
|
+
from textual.containers import Horizontal, Vertical
|
|
13
|
+
from textual.screen import ModalScreen
|
|
14
|
+
from textual.widgets import Button, Label, RichLog, Static
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ElevationModal(ModalScreen[str]):
|
|
18
|
+
"""Prompt the user to restart with Administrator / root privileges before running a privileged task."""
|
|
19
|
+
|
|
20
|
+
CSS = """
|
|
21
|
+
ElevationModal {
|
|
22
|
+
align: center middle;
|
|
23
|
+
}
|
|
24
|
+
#modal-box {
|
|
25
|
+
width: 66;
|
|
26
|
+
height: auto;
|
|
27
|
+
background: $panel;
|
|
28
|
+
border: round $warning;
|
|
29
|
+
padding: 1 2;
|
|
30
|
+
}
|
|
31
|
+
#modal-title {
|
|
32
|
+
color: $warning;
|
|
33
|
+
text-style: bold;
|
|
34
|
+
margin-bottom: 1;
|
|
35
|
+
}
|
|
36
|
+
#modal-body {
|
|
37
|
+
margin-bottom: 1;
|
|
38
|
+
}
|
|
39
|
+
.modal-buttons {
|
|
40
|
+
height: auto;
|
|
41
|
+
align: right middle;
|
|
42
|
+
}
|
|
43
|
+
Button {
|
|
44
|
+
margin-left: 1;
|
|
45
|
+
}
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
BINDINGS: ClassVar[list[Binding]] = [Binding("escape", "cancel", "Cancel")]
|
|
49
|
+
|
|
50
|
+
def __init__(self, action_name: str) -> None:
|
|
51
|
+
super().__init__()
|
|
52
|
+
self.action_name = action_name
|
|
53
|
+
|
|
54
|
+
def compose(self) -> ComposeResult:
|
|
55
|
+
with Vertical(id="modal-box"):
|
|
56
|
+
yield Label("Administrator Privileges Required", id="modal-title")
|
|
57
|
+
yield Static(
|
|
58
|
+
f"'{self.action_name}' requires Administrator (Windows) or root/sudo (Linux) privileges.\n\n"
|
|
59
|
+
"Running without elevation will fail with an access error.\n"
|
|
60
|
+
"Would you like to restart SysMaint as Administrator now?",
|
|
61
|
+
id="modal-body",
|
|
62
|
+
)
|
|
63
|
+
with Horizontal(classes="modal-buttons"):
|
|
64
|
+
yield Button("Cancel", id="btn-elev-cancel", variant="default")
|
|
65
|
+
yield Button("Restart as Administrator", id="btn-elev-go", variant="warning")
|
|
66
|
+
|
|
67
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
68
|
+
if event.button.id == "btn-elev-go":
|
|
69
|
+
self.dismiss("elevate")
|
|
70
|
+
else:
|
|
71
|
+
self.dismiss("cancel")
|
|
72
|
+
|
|
73
|
+
def action_cancel(self) -> None:
|
|
74
|
+
self.dismiss("cancel")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ConfirmLongTaskModal(ModalScreen[bool]):
|
|
78
|
+
"""Warn users before starting a long-running operation."""
|
|
79
|
+
|
|
80
|
+
CSS = """
|
|
81
|
+
ConfirmLongTaskModal {
|
|
82
|
+
align: center middle;
|
|
83
|
+
}
|
|
84
|
+
#long-box {
|
|
85
|
+
width: 68;
|
|
86
|
+
height: auto;
|
|
87
|
+
background: $panel;
|
|
88
|
+
border: round $primary;
|
|
89
|
+
padding: 1 2;
|
|
90
|
+
}
|
|
91
|
+
#long-title {
|
|
92
|
+
color: $primary;
|
|
93
|
+
text-style: bold;
|
|
94
|
+
margin-bottom: 1;
|
|
95
|
+
}
|
|
96
|
+
#long-body {
|
|
97
|
+
margin-bottom: 1;
|
|
98
|
+
}
|
|
99
|
+
.modal-buttons {
|
|
100
|
+
height: auto;
|
|
101
|
+
align: right middle;
|
|
102
|
+
}
|
|
103
|
+
Button {
|
|
104
|
+
margin-left: 1;
|
|
105
|
+
}
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
BINDINGS: ClassVar[list[Binding]] = [Binding("escape", "cancel", "Cancel")]
|
|
109
|
+
|
|
110
|
+
def __init__(self, task_name: str, estimate: str, details: str) -> None:
|
|
111
|
+
super().__init__()
|
|
112
|
+
self.task_name = task_name
|
|
113
|
+
self.estimate = estimate
|
|
114
|
+
self.details = details
|
|
115
|
+
|
|
116
|
+
def compose(self) -> ComposeResult:
|
|
117
|
+
with Vertical(id="long-box"):
|
|
118
|
+
yield Label(f"Start {self.task_name}?", id="long-title")
|
|
119
|
+
yield Static(
|
|
120
|
+
f"{self.details}\n\n"
|
|
121
|
+
f"Estimated time: {self.estimate}\n\n"
|
|
122
|
+
"Tip: You can minimize this window to the background while it runs. "
|
|
123
|
+
"SysMaint will display live progress and real percentage updates as the command runs.",
|
|
124
|
+
id="long-body",
|
|
125
|
+
)
|
|
126
|
+
with Horizontal(classes="modal-buttons"):
|
|
127
|
+
yield Button("Cancel", id="btn-long-cancel", variant="default")
|
|
128
|
+
yield Button("Start Now", id="btn-long-start", variant="success")
|
|
129
|
+
|
|
130
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
131
|
+
self.dismiss(event.button.id == "btn-long-start")
|
|
132
|
+
|
|
133
|
+
def action_cancel(self) -> None:
|
|
134
|
+
self.dismiss(False)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class TechnicalLogModal(ModalScreen[None]):
|
|
138
|
+
"""Full-window modal viewer for detailed technical logs and raw command output."""
|
|
139
|
+
|
|
140
|
+
CSS = """
|
|
141
|
+
TechnicalLogModal {
|
|
142
|
+
align: center middle;
|
|
143
|
+
}
|
|
144
|
+
#log-window {
|
|
145
|
+
width: 92%;
|
|
146
|
+
height: 88%;
|
|
147
|
+
background: $surface;
|
|
148
|
+
border: round $primary;
|
|
149
|
+
padding: 1 2;
|
|
150
|
+
}
|
|
151
|
+
#log-header {
|
|
152
|
+
height: auto;
|
|
153
|
+
margin-bottom: 1;
|
|
154
|
+
}
|
|
155
|
+
#log-title {
|
|
156
|
+
width: 1fr;
|
|
157
|
+
color: $primary;
|
|
158
|
+
text-style: bold;
|
|
159
|
+
}
|
|
160
|
+
#full-tech-log {
|
|
161
|
+
height: 1fr;
|
|
162
|
+
background: $background;
|
|
163
|
+
border: round $panel;
|
|
164
|
+
padding: 1;
|
|
165
|
+
}
|
|
166
|
+
Button {
|
|
167
|
+
margin-left: 1;
|
|
168
|
+
}
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
BINDINGS: ClassVar[list[Binding]] = [Binding("escape", "close_log", "Close")]
|
|
172
|
+
|
|
173
|
+
def __init__(self, entries: list[tuple[str, Any]]) -> None:
|
|
174
|
+
super().__init__()
|
|
175
|
+
self.entries = entries
|
|
176
|
+
|
|
177
|
+
def compose(self) -> ComposeResult:
|
|
178
|
+
with Vertical(id="log-window"):
|
|
179
|
+
with Horizontal(id="log-header"):
|
|
180
|
+
yield Label("Technical Activity Log (Full View)", id="log-title")
|
|
181
|
+
yield Button("Clear", id="btn-log-clear", variant="warning")
|
|
182
|
+
yield Button("Close (Esc)", id="btn-log-close", variant="primary")
|
|
183
|
+
yield RichLog(id="full-tech-log", wrap=True, highlight=True)
|
|
184
|
+
|
|
185
|
+
def on_mount(self) -> None:
|
|
186
|
+
log = self.query_one("#full-tech-log", RichLog)
|
|
187
|
+
if not self.entries:
|
|
188
|
+
log.write("No technical logs recorded yet. Run a scan or check to see full output here.")
|
|
189
|
+
return
|
|
190
|
+
for title, data in self.entries:
|
|
191
|
+
log.write(Panel(RichJSON(json.dumps(data, default=str)), title=title, border_style="cyan"))
|
|
192
|
+
|
|
193
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
194
|
+
if event.button.id == "btn-log-clear":
|
|
195
|
+
self.entries.clear()
|
|
196
|
+
self.query_one("#full-tech-log", RichLog).clear()
|
|
197
|
+
else:
|
|
198
|
+
self.dismiss(None)
|
|
199
|
+
|
|
200
|
+
def action_close_log(self) -> None:
|
|
201
|
+
self.dismiss(None)
|
sysmaint/tui/themes.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# src/sysmaint/tui/themes.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from textual.theme import Theme
|
|
6
|
+
|
|
7
|
+
OBSIDIAN_GOLD = Theme(
|
|
8
|
+
name="obsidian-gold",
|
|
9
|
+
primary="#facc15", # Radiant gold/yellow outlines
|
|
10
|
+
secondary="#f59e0b", # Warm amber
|
|
11
|
+
accent="#fde047", # Bright highlight yellow
|
|
12
|
+
foreground="#f8fafc",
|
|
13
|
+
background="#090b10", # Deep obsidian dark
|
|
14
|
+
surface="#111520",
|
|
15
|
+
panel="#171c2b",
|
|
16
|
+
success="#4ade80",
|
|
17
|
+
warning="#fbbf24",
|
|
18
|
+
error="#f87171",
|
|
19
|
+
dark=True,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
AMBER_SLATE = Theme(
|
|
23
|
+
name="amber-slate",
|
|
24
|
+
primary="#ca8a04", # Dark golden yellow
|
|
25
|
+
secondary="#eab308",
|
|
26
|
+
accent="#fde047",
|
|
27
|
+
foreground="#f3f4f6",
|
|
28
|
+
background="#18191f", # Dark grey/charcoal
|
|
29
|
+
surface="#1f2128",
|
|
30
|
+
panel="#272a34",
|
|
31
|
+
success="#4ade80",
|
|
32
|
+
warning="#facc15",
|
|
33
|
+
error="#fb7185",
|
|
34
|
+
dark=True,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
EMERALD_NOIR = Theme(
|
|
38
|
+
name="emerald-noir",
|
|
39
|
+
primary="#34d399", # Radiant emerald
|
|
40
|
+
secondary="#10b981",
|
|
41
|
+
accent="#6ee7b7",
|
|
42
|
+
foreground="#ecfdf5",
|
|
43
|
+
background="#070b09",
|
|
44
|
+
surface="#0e1612",
|
|
45
|
+
panel="#14201a",
|
|
46
|
+
success="#34d399",
|
|
47
|
+
warning="#fbbf24",
|
|
48
|
+
error="#fb7185",
|
|
49
|
+
dark=True,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
CYBER_COBALT = Theme(
|
|
53
|
+
name="cyber-cobalt",
|
|
54
|
+
primary="#22d3ee", # Electric cyan
|
|
55
|
+
secondary="#38bdf8",
|
|
56
|
+
accent="#67e8f9",
|
|
57
|
+
foreground="#f0f9ff",
|
|
58
|
+
background="#080d1a",
|
|
59
|
+
surface="#0f172a",
|
|
60
|
+
panel="#16223d",
|
|
61
|
+
success="#4ade80",
|
|
62
|
+
warning="#facc15",
|
|
63
|
+
error="#f87171",
|
|
64
|
+
dark=True,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
CATPPUCCIN_MOCHA = Theme(
|
|
68
|
+
name="catppuccin-mocha",
|
|
69
|
+
primary="#89b4fa",
|
|
70
|
+
secondary="#74c7ec",
|
|
71
|
+
accent="#94e2d5",
|
|
72
|
+
foreground="#cdd6f4",
|
|
73
|
+
background="#1e1e2e",
|
|
74
|
+
surface="#181825",
|
|
75
|
+
panel="#313244",
|
|
76
|
+
success="#a6e3a1",
|
|
77
|
+
warning="#f9e2af",
|
|
78
|
+
error="#f38ba8",
|
|
79
|
+
dark=True,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
CUSTOM_THEMES = [
|
|
83
|
+
OBSIDIAN_GOLD,
|
|
84
|
+
AMBER_SLATE,
|
|
85
|
+
EMERALD_NOIR,
|
|
86
|
+
CYBER_COBALT,
|
|
87
|
+
CATPPUCCIN_MOCHA,
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
THEME_CYCLE = [
|
|
91
|
+
"obsidian-gold",
|
|
92
|
+
"amber-slate",
|
|
93
|
+
"emerald-noir",
|
|
94
|
+
"cyber-cobalt",
|
|
95
|
+
"catppuccin-mocha",
|
|
96
|
+
"tokyo-night",
|
|
97
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# sysmaint/utils/__init__.py
|
|
2
|
+
|
|
3
|
+
from .common import (
|
|
4
|
+
compute_sha256,
|
|
5
|
+
extract_progress_percent,
|
|
6
|
+
format_bytes,
|
|
7
|
+
run_command,
|
|
8
|
+
safe_delete_dir_contents,
|
|
9
|
+
safe_delete_file,
|
|
10
|
+
stream_command,
|
|
11
|
+
)
|
|
12
|
+
from .escalate import ensure_elevated, is_elevated, request_elevation
|
|
13
|
+
from .parsers import (
|
|
14
|
+
parse_clamscan_output,
|
|
15
|
+
parse_dism_output,
|
|
16
|
+
parse_driverquery_output,
|
|
17
|
+
parse_fsck_output,
|
|
18
|
+
parse_ping_output,
|
|
19
|
+
parse_sfc_output,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"compute_sha256",
|
|
24
|
+
"ensure_elevated",
|
|
25
|
+
"extract_progress_percent",
|
|
26
|
+
"format_bytes",
|
|
27
|
+
"is_elevated",
|
|
28
|
+
"parse_clamscan_output",
|
|
29
|
+
"parse_dism_output",
|
|
30
|
+
"parse_driverquery_output",
|
|
31
|
+
"parse_fsck_output",
|
|
32
|
+
"parse_ping_output",
|
|
33
|
+
"parse_sfc_output",
|
|
34
|
+
"request_elevation",
|
|
35
|
+
"run_command",
|
|
36
|
+
"safe_delete_dir_contents",
|
|
37
|
+
"safe_delete_file",
|
|
38
|
+
"stream_command",
|
|
39
|
+
]
|
sysmaint/utils/common.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
# sysmaint/utils/common.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
from collections.abc import Callable, Iterable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("sysmaint.utils")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def run_command(
|
|
17
|
+
command: Iterable[str],
|
|
18
|
+
*,
|
|
19
|
+
check: bool = False,
|
|
20
|
+
timeout: int | None = None,
|
|
21
|
+
capture_output: bool = True,
|
|
22
|
+
shell: bool = False,
|
|
23
|
+
cwd: str | Path | None = None,
|
|
24
|
+
) -> subprocess.CompletedProcess[str]:
|
|
25
|
+
"""
|
|
26
|
+
Run a system command safely with structured logging and error handling.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
command: Iterable of command and arguments, or string if shell=True.
|
|
30
|
+
check: If True, raise CalledProcessError on non-zero return code.
|
|
31
|
+
timeout: Optional timeout in seconds.
|
|
32
|
+
capture_output: If True, capture stdout and stderr as text.
|
|
33
|
+
shell: Whether to execute command through the shell.
|
|
34
|
+
cwd: Working directory.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
subprocess.CompletedProcess with text stdout/stderr.
|
|
38
|
+
"""
|
|
39
|
+
if isinstance(command, str) and not shell or isinstance(command, str) and shell:
|
|
40
|
+
cmd_list = [command]
|
|
41
|
+
else:
|
|
42
|
+
cmd_list = list(command)
|
|
43
|
+
|
|
44
|
+
display_cmd = cmd_list[0] if shell and isinstance(command, str) else " ".join(cmd_list)
|
|
45
|
+
logger.debug("Executing command: %s", display_cmd)
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
result = subprocess.run(
|
|
49
|
+
cmd_list if not shell else display_cmd,
|
|
50
|
+
capture_output=capture_output,
|
|
51
|
+
text=True,
|
|
52
|
+
check=check,
|
|
53
|
+
timeout=timeout,
|
|
54
|
+
shell=shell,
|
|
55
|
+
cwd=cwd,
|
|
56
|
+
encoding="utf-8",
|
|
57
|
+
errors="replace",
|
|
58
|
+
)
|
|
59
|
+
except subprocess.TimeoutExpired:
|
|
60
|
+
logger.error("Command timed out after %ds: %s", timeout, display_cmd)
|
|
61
|
+
return subprocess.CompletedProcess(
|
|
62
|
+
args=cmd_list,
|
|
63
|
+
returncode=-1,
|
|
64
|
+
stdout="",
|
|
65
|
+
stderr=f"Command timed out after {timeout} seconds",
|
|
66
|
+
)
|
|
67
|
+
except subprocess.CalledProcessError as exc:
|
|
68
|
+
logger.error("Command failed (rc=%d): %s\n%s", exc.returncode, display_cmd, exc.stderr)
|
|
69
|
+
raise
|
|
70
|
+
except FileNotFoundError:
|
|
71
|
+
logger.warning("Command executable not found: %s", cmd_list[0] if cmd_list else "")
|
|
72
|
+
return subprocess.CompletedProcess(
|
|
73
|
+
args=cmd_list,
|
|
74
|
+
returncode=127,
|
|
75
|
+
stdout="",
|
|
76
|
+
stderr=f"Executable not found: {cmd_list[0] if cmd_list else ''}",
|
|
77
|
+
)
|
|
78
|
+
except Exception as exc:
|
|
79
|
+
logger.error("Unexpected error executing %s: %s", display_cmd, exc)
|
|
80
|
+
return subprocess.CompletedProcess(
|
|
81
|
+
args=cmd_list,
|
|
82
|
+
returncode=-1,
|
|
83
|
+
stdout="",
|
|
84
|
+
stderr=str(exc),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
if result.returncode != 0:
|
|
88
|
+
logger.debug(
|
|
89
|
+
"Command returned %d: %s\nstderr: %s",
|
|
90
|
+
result.returncode,
|
|
91
|
+
display_cmd,
|
|
92
|
+
result.stderr.strip() if result.stderr else "",
|
|
93
|
+
)
|
|
94
|
+
return result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_PERCENT_RE = re.compile(r"(\d{1,3}(?:\.\d+)?)\s*(?:%|percent)", re.IGNORECASE)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def extract_progress_percent(line: str) -> float | None:
|
|
101
|
+
"""Extract a real percentage (0-100) from command output lines (DISM, SFC, chkdsk)."""
|
|
102
|
+
match = _PERCENT_RE.search(line)
|
|
103
|
+
if not match:
|
|
104
|
+
return None
|
|
105
|
+
val = float(match.group(1))
|
|
106
|
+
if 0.0 <= val <= 100.0:
|
|
107
|
+
return val
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def stream_command(
|
|
112
|
+
command: Iterable[str],
|
|
113
|
+
*,
|
|
114
|
+
on_line: Callable[[str, float | None], None] | None = None,
|
|
115
|
+
cwd: str | Path | None = None,
|
|
116
|
+
) -> subprocess.CompletedProcess[str]:
|
|
117
|
+
"""
|
|
118
|
+
Execute a command while streaming live output lines and parsed percentages.
|
|
119
|
+
Handles both '\\n' and '\\r' updates used by tools like DISM and SFC.
|
|
120
|
+
"""
|
|
121
|
+
cmd_list = [command] if isinstance(command, str) else list(command)
|
|
122
|
+
captured: list[str] = []
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
proc = subprocess.Popen(
|
|
126
|
+
cmd_list,
|
|
127
|
+
stdout=subprocess.PIPE,
|
|
128
|
+
stderr=subprocess.STDOUT,
|
|
129
|
+
text=True,
|
|
130
|
+
cwd=cwd,
|
|
131
|
+
encoding="utf-8",
|
|
132
|
+
errors="replace",
|
|
133
|
+
bufsize=1,
|
|
134
|
+
)
|
|
135
|
+
except FileNotFoundError:
|
|
136
|
+
msg = f"Executable not found: {cmd_list[0] if cmd_list else ''}"
|
|
137
|
+
if on_line:
|
|
138
|
+
on_line(msg, None)
|
|
139
|
+
return subprocess.CompletedProcess(args=cmd_list, returncode=127, stdout="", stderr=msg)
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
if on_line:
|
|
142
|
+
on_line(str(exc), None)
|
|
143
|
+
return subprocess.CompletedProcess(args=cmd_list, returncode=-1, stdout="", stderr=str(exc))
|
|
144
|
+
|
|
145
|
+
assert proc.stdout is not None
|
|
146
|
+
buf = ""
|
|
147
|
+
while True:
|
|
148
|
+
ch = proc.stdout.read(1)
|
|
149
|
+
if not ch:
|
|
150
|
+
if buf.strip():
|
|
151
|
+
line = buf.strip()
|
|
152
|
+
captured.append(line)
|
|
153
|
+
if on_line:
|
|
154
|
+
on_line(line, extract_progress_percent(line))
|
|
155
|
+
break
|
|
156
|
+
if ch in ("\r", "\n"):
|
|
157
|
+
line = buf.strip()
|
|
158
|
+
buf = ""
|
|
159
|
+
if line:
|
|
160
|
+
captured.append(line)
|
|
161
|
+
if on_line:
|
|
162
|
+
on_line(line, extract_progress_percent(line))
|
|
163
|
+
else:
|
|
164
|
+
buf += ch
|
|
165
|
+
|
|
166
|
+
rc = proc.wait()
|
|
167
|
+
return subprocess.CompletedProcess(
|
|
168
|
+
args=cmd_list,
|
|
169
|
+
returncode=rc,
|
|
170
|
+
stdout="\n".join(captured),
|
|
171
|
+
stderr="",
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def format_bytes(num_bytes: float) -> str:
|
|
176
|
+
"""
|
|
177
|
+
Convert a byte count into a human-readable string (e.g., '14.2 GB', '512 KB').
|
|
178
|
+
"""
|
|
179
|
+
if num_bytes < 0:
|
|
180
|
+
return "0 B"
|
|
181
|
+
for unit in ["B", "KB", "MB", "GB", "TB", "PB"]:
|
|
182
|
+
if abs(num_bytes) < 1024.0:
|
|
183
|
+
if unit in ("B", "KB"):
|
|
184
|
+
return f"{num_bytes:.0f} {unit}"
|
|
185
|
+
return f"{num_bytes:.2f} {unit}"
|
|
186
|
+
num_bytes /= 1024.0
|
|
187
|
+
return f"{num_bytes:.2f} EB"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def compute_sha256(file_path: str | Path, chunk_size: int = 65536) -> str | None:
|
|
191
|
+
"""
|
|
192
|
+
Compute SHA-256 hash of a file safely in chunks.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
Hex-encoded SHA-256 string or None if unreadable.
|
|
196
|
+
"""
|
|
197
|
+
path = Path(file_path)
|
|
198
|
+
if not path.is_file():
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
sha256 = hashlib.sha256()
|
|
202
|
+
try:
|
|
203
|
+
with open(path, "rb") as f:
|
|
204
|
+
while chunk := f.read(chunk_size):
|
|
205
|
+
sha256.update(chunk)
|
|
206
|
+
return sha256.hexdigest()
|
|
207
|
+
except (PermissionError, OSError) as exc:
|
|
208
|
+
logger.warning("Could not compute hash for %s: %s", file_path, exc)
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def safe_delete_file(file_path: str | Path) -> tuple[bool, int]:
|
|
213
|
+
"""
|
|
214
|
+
Safely delete a file, returning (success, bytes_freed).
|
|
215
|
+
"""
|
|
216
|
+
path = Path(file_path)
|
|
217
|
+
try:
|
|
218
|
+
if path.is_file() or path.is_symlink():
|
|
219
|
+
size = path.stat().st_size
|
|
220
|
+
path.unlink(missing_ok=True)
|
|
221
|
+
return True, size
|
|
222
|
+
except (PermissionError, OSError) as exc:
|
|
223
|
+
logger.debug("Failed to delete file %s: %s", file_path, exc)
|
|
224
|
+
return False, 0
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def safe_delete_dir_contents(dir_path: str | Path) -> tuple[int, int]:
|
|
228
|
+
"""
|
|
229
|
+
Safely delete all files and subdirectories inside a folder without deleting the folder itself.
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
tuple of (files_deleted_count, bytes_freed)
|
|
233
|
+
"""
|
|
234
|
+
path = Path(dir_path)
|
|
235
|
+
if not path.is_dir():
|
|
236
|
+
return 0, 0
|
|
237
|
+
|
|
238
|
+
files_deleted = 0
|
|
239
|
+
bytes_freed = 0
|
|
240
|
+
|
|
241
|
+
for root, dirs, files in os.walk(path, topdown=False):
|
|
242
|
+
for f in files:
|
|
243
|
+
fp = Path(root) / f
|
|
244
|
+
success, size = safe_delete_file(fp)
|
|
245
|
+
if success:
|
|
246
|
+
files_deleted += 1
|
|
247
|
+
bytes_freed += size
|
|
248
|
+
for d in dirs:
|
|
249
|
+
dp = Path(root) / d
|
|
250
|
+
try:
|
|
251
|
+
dp.rmdir()
|
|
252
|
+
except OSError:
|
|
253
|
+
pass
|
|
254
|
+
|
|
255
|
+
return files_deleted, bytes_freed
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# sysmaint/utils/escalate.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ctypes
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger("sysmaint.escalate")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def is_elevated() -> bool:
|
|
15
|
+
"""
|
|
16
|
+
Check if the current process is running with elevated privileges (Admin/root).
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
True if running as Administrator on Windows or root on Linux/macOS.
|
|
20
|
+
"""
|
|
21
|
+
if os.name == "nt":
|
|
22
|
+
try:
|
|
23
|
+
return bool(ctypes.windll.shell32.IsUserAnAdmin())
|
|
24
|
+
except (AttributeError, OSError):
|
|
25
|
+
return False
|
|
26
|
+
else:
|
|
27
|
+
try:
|
|
28
|
+
return os.geteuid() == 0
|
|
29
|
+
except AttributeError:
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def request_elevation(
|
|
34
|
+
args: list[str] | None = None,
|
|
35
|
+
exit_on_relaunch: bool = True,
|
|
36
|
+
) -> bool:
|
|
37
|
+
"""
|
|
38
|
+
Request elevated privileges by re-launching the process.
|
|
39
|
+
|
|
40
|
+
Windows: Triggers a UAC prompt using ShellExecuteW with the 'runas' verb.
|
|
41
|
+
Linux/macOS: Spawns sudo / pkexec.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
args: Optional custom command-line arguments. Defaults to current sys.argv[1:].
|
|
45
|
+
exit_on_relaunch: Whether to exit current non-elevated process upon successful launch.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
True if already elevated or if elevation process was launched.
|
|
49
|
+
"""
|
|
50
|
+
if is_elevated():
|
|
51
|
+
return True
|
|
52
|
+
|
|
53
|
+
cmd_args = sys.argv[1:] if args is None else args
|
|
54
|
+
|
|
55
|
+
if os.name == "nt":
|
|
56
|
+
logger.info("Requesting administrative elevation via Windows UAC...")
|
|
57
|
+
params = subprocess.list2cmdline(cmd_args)
|
|
58
|
+
ret = ctypes.windll.shell32.ShellExecuteW(
|
|
59
|
+
None,
|
|
60
|
+
"runas",
|
|
61
|
+
sys.executable,
|
|
62
|
+
params,
|
|
63
|
+
None,
|
|
64
|
+
1, # SW_SHOWNORMAL
|
|
65
|
+
)
|
|
66
|
+
if ret > 32:
|
|
67
|
+
logger.info("Elevated process spawned successfully.")
|
|
68
|
+
if exit_on_relaunch:
|
|
69
|
+
sys.exit(0)
|
|
70
|
+
return True
|
|
71
|
+
else:
|
|
72
|
+
logger.warning("UAC elevation was cancelled or failed (code %d).", ret)
|
|
73
|
+
return False
|
|
74
|
+
else:
|
|
75
|
+
logger.info("Requesting root elevation via sudo...")
|
|
76
|
+
try:
|
|
77
|
+
sudo_cmd = ["sudo", sys.executable] + sys.argv
|
|
78
|
+
result = subprocess.run(sudo_cmd, check=False)
|
|
79
|
+
if exit_on_relaunch:
|
|
80
|
+
sys.exit(result.returncode)
|
|
81
|
+
return result.returncode == 0
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
logger.error("Failed to execute sudo: %s", exc)
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def ensure_elevated() -> None:
|
|
88
|
+
"""
|
|
89
|
+
Ensure the process is running as root or administrator.
|
|
90
|
+
If not, re-launches with elevated privileges.
|
|
91
|
+
"""
|
|
92
|
+
if not is_elevated():
|
|
93
|
+
request_elevation(exit_on_relaunch=True)
|