40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
import asyncio
|
|
from os import PathLike
|
|
from pathlib import Path
|
|
|
|
|
|
class LinuxUtils:
|
|
"""Utilities for Linux-specific tasks."""
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
@staticmethod
|
|
async def _exec_command(args):
|
|
"""Execute a command using pkexec (friendly gui)"""
|
|
if not Path("/usr/bin/pkexec").is_file():
|
|
raise FileNotFoundError("pkexec not found.")
|
|
rsp = await asyncio.create_subprocess_shell(args)
|
|
await rsp.wait()
|
|
match rsp.returncode:
|
|
case 127:
|
|
raise OSError("Authentication failed.")
|
|
case 128:
|
|
raise RuntimeError("User cancelled the authentication.")
|
|
|
|
return rsp
|
|
|
|
async def write_text_to_file(self, text, file_path: PathLike):
|
|
"""Write text to a file using pkexec (friendly gui)"""
|
|
if isinstance(file_path, Path):
|
|
file_path = str(file_path)
|
|
await self._exec_command('echo -e "{}" | pkexec tee {}'.format(text, file_path))
|
|
|
|
async def append_text_to_file(self, text, file_path: PathLike):
|
|
"""Append text to a file using pkexec (friendly gui)"""
|
|
if isinstance(file_path, Path):
|
|
file_path = str(file_path)
|
|
await self._exec_command(
|
|
'echo -e "{}" | pkexec tee -a {}'.format(text, file_path)
|
|
)
|