import re CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml" SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml" sec = open(SEC, encoding="utf-8").read() if "nextcloud_auth" not in sec: import base64 token = base64.b64encode(("roman:" + open("/root/.nextcloud-admin-pass").read().strip()).encode()).decode() with open(SEC, "a", encoding="utf-8") as f: f.write(f'\nnextcloud_auth: "Basic {token}"\n') print(" секрет Nextcloud добавлен") block = ''' - resource: http://192.168.1.109:8080/ocs/v2.php/cloud/users/roman?format=json headers: Authorization: !secret nextcloud_auth OCS-APIRequest: "true" Accept: application/json scan_interval: 600 sensor: - name: "Nextcloud занято" unique_id: nextcloud_used_gb value_template: "{{ (value_json.ocs.data.quota.used / 1073741824) | round(2) }}" unit_of_measurement: "ГБ" - name: "Nextcloud вход" unique_id: nextcloud_last_login value_template: "{{ value_json.ocs.data.lastLoginTimestamp | int(0) | timestamp_local }}" device_class: timestamp ''' s = open(CFG, encoding="utf-8").read() if "nextcloud_used_gb" 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(" сенсоры добавлены")