Skip to content

Instantly share code, notes, and snippets.

@meanother
Created January 19, 2024 13:42
Show Gist options
  • Save meanother/75410675f817653aeb92ff4a62a6f6d4 to your computer and use it in GitHub Desktop.
Save meanother/75410675f817653aeb92ff4a62a6f6d4 to your computer and use it in GitHub Desktop.
systemctl table
#!/root/env/bin/python
import subprocess
from prettytable import PrettyTable
services = [
"wg-quick@wg0",
"wg-bot",
"wg-slave",
"wg-payments",
"marzban",
"xray",
"marzban-gateway",
"nginx",
"postgresql",
]
def _get_value(row: str) -> str:
return " ".join(row.split(": ")[1:])
def _get_status(value: str) -> str:
if "active" in value:
return "🟢"
return "🔴"
def _get_uptime(value: str) -> str:
return value.split(";")[1].strip()
def _check_status(service_name: str) -> dict:
data = {
"name": None,
"memory": None,
"status": None,
"uptime": None,
"tasks": None,
"pid": None
}
try:
result = subprocess.check_output(["systemctl", "status", service_name]).strip().decode()
result_rows = result.split("\n")
for row in result_rows:
data["name"] = service_name
row = row.strip()
if row.startswith("Memory:"):
data["memory"] = _get_value(row)
elif row.startswith("Active:"):
data["status"] = _get_status(_get_value(row))
data["uptime"] = _get_uptime(_get_value(row))
elif row.startswith("Tasks:"):
data["tasks"] = _get_value(row).replace(" (limit ", "/").replace(")", "")
elif row.startswith("Main PID:"):
data["pid"] = _get_value(row).split(" ")[0]
return data
except subprocess.CalledProcessError as e:
print(e)
return {}
def show_table() -> None:
table = PrettyTable()
table.title = "Systemctl status"
data = []
for service in services:
result = _check_status(service)
data.append(result)
table.add_row(list(result.values()))
table.field_names = list(data[0].keys())
print(table)
show_table()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment