Files
buryan-infra/ops/homeassistant/add_more.py
T
buryan-agent 7eb16614d5 HA: REST-сенсоры Proxmox, Authentik, Prometheus
Создан API-токен monitoring@pve!ha-token с ролью PVEAuditor; добавлены
сенсоры: CPU, RAM, uptime, диск Proxmox; число пользователей Authentik;
онлайн-цели Prometheus.

Интеграция proxmoxve из HACS сущностей не создаёт — заменена сенсорами.
Frigate API и Jellyfin-ключ недоступны; Uptime Kuma не имеет REST (socket.io),
но 18 мониторов уже работают.
2026-10-20 18:39:36 +03:00

79 lines
2.9 KiB
Python

"""Добавляет REST-сенсоры сервисов и убирает нерабочую запись proxmoxve."""
import json
import os
import re
import urllib.request
CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml"
SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml"
AK = open("/tmp/authentik-token", encoding="utf-8").read().strip()
sec = open(SEC, encoding="utf-8").read()
if "authentik_api_token" not in sec:
with open(SEC, "a", encoding="utf-8") as f:
f.write(f'\nauthentik_api_token: "Bearer {AK}"\n')
print(" секрет Authentik добавлен")
block = ''' - resource: http://192.168.1.114:9000/api/v3/core/users/?page_size=1
headers:
Authorization: !secret authentik_api_token
scan_interval: 300
sensor:
- name: "Authentik пользователей"
unique_id: authentik_users_count
value_template: "{{ value_json.pagination.count }}"
- resource: http://192.168.1.134:9090/api/v1/query?query=count(up%3D%3D1)
scan_interval: 120
sensor:
- name: "Prometheus целей онлайн"
unique_id: prometheus_targets_up
value_template: "{{ value_json.data.result[0].value[1] | int }}"
- resource: http://192.168.1.125:4533/rest/ping.view
scan_interval: 180
sensor:
- name: "Navidrome статус"
unique_id: navidrome_status
value_template: "{{ value_json['subsonic-response'].status }}"
'''
s = open(CFG, encoding="utf-8").read()
if "authentik_users_count" in s:
print(" сенсоры уже есть")
else:
lines = s.split("\n")
start = next((i for i, l in enumerate(lines) if re.match(r"^rest:\s*$", l)), None)
if start is None:
s = s.rstrip() + "\n\nrest:\n" + block
else:
end = len(lines)
for j in range(start + 1, len(lines)):
if lines[j] and not lines[j].startswith((" ", "\t")) and not lines[j].startswith("#"):
end = j
break
lines[end:end] = block.split("\n")
s = "\n".join(lines)
open(CFG, "w", encoding="utf-8").write(s)
print(" сенсоры добавлены")
# удаляем proxmoxve entry
TOK = open("/tmp/ha-token", encoding="utf-8").read().strip()
H = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"}
def call(p, m="GET", b=None):
d = json.dumps(b).encode() if b is not None else None
r = urllib.request.Request("http://127.0.0.1:8123" + p, data=d, method=m, headers=H)
try:
with urllib.request.urlopen(r, timeout=40) as x:
raw = x.read()
return (json.loads(raw) if raw else {}), None
except Exception as e:
return None, str(e)[:80]
entries, _ = call("/api/config/config_entries/entry")
for e in entries or []:
if e.get("domain") == "proxmoxve":
call(f"/api/config/config_entries/entry/{e['entry_id']}", "DELETE")
print(" proxmoxve-запись удалена (сущностей не создавала)")