2022-02-26 18:54:20 +00:00
|
|
|
import asyncio
|
|
|
|
from pathlib import Path
|
2022-06-24 18:13:47 +00:00
|
|
|
from aiopath import AsyncPath
|
2022-02-26 18:54:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LinuxUtils:
|
|
|
|
"""Utilities for Linux-specific tasks.
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
pass
|
|
|
|
|
2022-06-24 18:13:47 +00:00
|
|
|
@staticmethod
|
|
|
|
async def _exec_command(args):
|
2022-02-26 18:54:20 +00:00
|
|
|
"""Execute a command using pkexec (friendly gui)
|
|
|
|
"""
|
2022-06-24 18:13:47 +00:00
|
|
|
if not await AsyncPath("/usr/bin/pkexec").exists():
|
|
|
|
raise FileNotFoundError("pkexec not found.")
|
2022-02-27 06:42:10 +00:00
|
|
|
rsp = await asyncio.create_subprocess_shell(args)
|
2022-02-27 06:36:57 +00:00
|
|
|
await rsp.wait()
|
2022-02-26 18:54:20 +00:00
|
|
|
match rsp.returncode:
|
|
|
|
case 127:
|
|
|
|
raise OSError("Authentication failed.")
|
|
|
|
case 128:
|
|
|
|
raise RuntimeError("User cancelled the authentication.")
|
|
|
|
|
|
|
|
return rsp
|
|
|
|
|
2022-06-24 18:13:47 +00:00
|
|
|
async def write_text_to_file(self, text, file_path: str | Path | AsyncPath):
|
2022-02-26 18:54:20 +00:00
|
|
|
"""Write text to a file using pkexec (friendly gui)
|
|
|
|
"""
|
2022-06-24 18:13:47 +00:00
|
|
|
if isinstance(file_path, Path | AsyncPath):
|
2022-02-26 18:54:20 +00:00
|
|
|
file_path = str(file_path)
|
2022-02-27 06:50:59 +00:00
|
|
|
await self._exec_command('echo -e "{}" | pkexec tee {}'.format(text, file_path))
|
2022-02-26 18:54:20 +00:00
|
|
|
|
2022-06-24 18:13:47 +00:00
|
|
|
async def append_text_to_file(self, text, file_path: str | Path | AsyncPath):
|
2022-02-26 18:54:20 +00:00
|
|
|
"""Append text to a file using pkexec (friendly gui)
|
|
|
|
"""
|
|
|
|
if isinstance(file_path, Path):
|
|
|
|
file_path = str(file_path)
|
2022-02-27 06:50:59 +00:00
|
|
|
await self._exec_command('echo -e "{}" | pkexec tee -a {}'.format(text, file_path))
|