#!/bin/env python ## Copyright 2023 Aleteoryx ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from os import scandir from datetime import datetime HOSTS = '/etc/hosts' HOSTS_D = '/etc/hosts.d/' def regen(): try: now = datetime.now().strftime('%a %d %b %Y, %H:%M:%S.%f') print(f'[{now}] -- Regenerating hosts...') acc = [f"### Generated @ {now}.\n"] for file in scandir(HOSTS_D): if file.is_file(): acc = [*acc, f"## BEGIN `{file.path}`\n", *open(file.path, encoding='L1').readlines(), f"## END `{file.path}`\n"] open(HOSTS, 'wt').writelines(acc) now = datetime.now().strftime('%a %d %b %Y, %H:%M:%S.%f') print(f'[{now}] -- Done.') except Exception as e: print(f'caught {e} while regenerating') class FSWatcher(FileSystemEventHandler): def on_modified(self, ev): if ev.is_directory: return regen() def on_deleted(self, ev): if ev.is_directory: return regen() def on_created(self, ev): if ev.is_directory: return regen() regen() observer = Observer() observer.schedule(FSWatcher(), HOSTS_D, recursive=True) observer.start() observer.join()