-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprivileged.py
More file actions
64 lines (44 loc) · 1.55 KB
/
Copy pathprivileged.py
File metadata and controls
64 lines (44 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from __future__ import annotations
import grp
import os
import shutil
import subprocess
from pathlib import Path
SUDOERS_PATH = Path("/etc/sudoers.d/amper")
GROUP_NAME = "amper"
SETUP_SCRIPT = Path(__file__).resolve().parent / "setup_permissions.sh"
def _run(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, capture_output=True, text=True, check=False)
def user_in_amper_group() -> bool:
try:
group_id = grp.getgrnam(GROUP_NAME).gr_gid
except KeyError:
return False
return group_id in os.getgroups()
def sudoers_installed() -> bool:
return SUDOERS_PATH.is_file()
def can_run_without_password() -> bool:
if not shutil.which("sudo"):
return False
if not sudoers_installed() or not user_in_amper_group():
return False
probe = _run(["sudo", "-n", "systemctl", "is-system-running"])
return probe.returncode in {0, 1}
def is_ready() -> bool:
return can_run_without_password()
def wrap(command: list[str]) -> list[str]:
if can_run_without_password():
return ["sudo", "-n", *command]
if shutil.which("pkexec"):
return ["pkexec", *command]
return command
def popen(command: list[str], **kwargs) -> subprocess.Popen:
return subprocess.Popen(
wrap(command),
stdout=kwargs.get("stdout", subprocess.DEVNULL),
stderr=kwargs.get("stderr", subprocess.DEVNULL),
)
def run(command: list[str]) -> subprocess.CompletedProcess[str]:
return _run(wrap(command))
def setup_script_path() -> Path:
return SETUP_SCRIPT