marc/pubnix.py

84 lines
2.3 KiB
Python
Raw Normal View History

2025-02-22 21:23:05 +01:00
from __future__ import annotations
2022-05-01 22:58:23 +02:00
import os
2025-02-18 22:05:22 +01:00
from pathlib import Path
2022-05-01 22:58:23 +02:00
import subprocess
PORT = 22
2025-02-18 20:58:05 +01:00
USER = "mspe"
ROOT = "public_html"
PROTOCOL = "https"
2022-05-01 22:58:23 +02:00
DIR = False
class PubNix:
2025-02-18 20:58:05 +01:00
def __init__(
self,
dn,
2025-02-22 21:23:05 +01:00
ssh: str | None = None,
2025-02-18 22:05:22 +01:00
port: int = PORT,
user: str = USER,
root: str = ROOT,
dir: bool = DIR,
2025-02-22 21:23:05 +01:00
web: str | None = None,
sub: bool | None = None,
2025-02-18 20:58:05 +01:00
):
2022-05-01 22:58:23 +02:00
self.dn = dn
2025-02-18 20:58:05 +01:00
self.ssh = f"{ssh}.{self.dn}" if ssh else self.dn
2022-05-01 22:58:23 +02:00
self.port = port
self.user = user
self.root = root
2025-02-18 20:58:05 +01:00
self.web = f"{web}.{self.dn}" if web else self.dn
2022-05-01 22:58:23 +02:00
if sub:
2025-02-18 20:58:05 +01:00
self.fqdn = f"{self.user}.{self.web}"
2022-05-01 22:58:23 +02:00
self.context = None
else:
self.fqdn = self.web
2025-02-18 20:58:05 +01:00
self.context = f"~{self.user}"
2025-02-18 22:05:22 +01:00
self.path = (Path(self.root) / self.fqdn) if dir else self.root
2025-02-18 20:58:05 +01:00
self.target = f"{self.user}@{self.ssh}:{self.path}"
2025-02-18 22:05:22 +01:00
self.url = [f"{PROTOCOL}:", "", self.fqdn]
2022-05-01 22:58:23 +02:00
if self.context:
self.url.append(self.context)
2025-02-18 20:58:05 +01:00
self.url = "/".join(self.url)
2022-05-01 22:58:23 +02:00
2023-10-08 15:00:44 +02:00
def capturun(self, *args):
return self.run(*args, capture_output=True)
def run(self, *args, **kwargs):
2025-02-18 20:58:05 +01:00
return subprocess.run(
[
"ssh",
"-o",
"LogLevel Error",
"-p",
str(self.port),
f"{self.user}@{self.ssh}",
"--",
*args,
],
**kwargs,
)
2022-05-01 22:58:23 +02:00
2025-02-18 22:05:22 +01:00
def disk_free(self) -> str:
2025-02-22 21:23:05 +01:00
"""Fetch free space information."""
2025-02-18 20:58:05 +01:00
process = self.capturun("df", "-h", os.curdir)
return process.stdout.decode("UTF-8").strip()
2023-10-08 15:00:44 +02:00
2025-02-18 22:05:22 +01:00
def os(self) -> str:
2025-02-22 21:23:05 +01:00
"""Fetch Operating System release information."""
2025-02-18 20:58:05 +01:00
ps = self.capturun("cat", "/etc/os-release")
2023-10-08 15:00:44 +02:00
if ps.returncode == 0:
2025-02-18 20:58:05 +01:00
for line in ps.stdout.decode("UTF-8").strip().split(os.linesep):
if "PRETTY_NAME" in line:
2025-02-22 21:23:05 +01:00
text = line.split("=")[1].split('"')[1]
break
else:
text = ""
return text
2023-10-08 15:00:44 +02:00
else:
2025-02-18 20:58:05 +01:00
return self.capturun("uname", "-sr").stdout.decode("UTF-8").strip()
2022-05-01 22:58:23 +02:00
2025-02-18 22:05:22 +01:00
def __str__(self) -> str:
"""Return target & url."""
2022-05-01 22:58:23 +02:00
return os.linesep.join([self.target, self.url])