2023_tacacs_watcher/main.py

128 lines
5.0 KiB
Python
Raw Permalink Normal View History

2023-12-15 15:58:31 +03:00
# -*- coding: utf-8 -*-
import platform
2023-12-15 15:58:31 +03:00
import time
import sys
import signal
import toml
import os
import subprocess
2023-12-15 15:58:31 +03:00
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from singleton import SingleInstance, SingleInstanceException
2023-12-15 15:58:31 +03:00
from pathlib import Path
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.\
# Обработчик сигнала SIGTERM (сигнал остановки от systemd)
def handler_stop(signum, frame) -> None:
print(f'Terminate by signal: {signum}')
sys.exit(0)
# Чтение файла конфигурации
def read_toml(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = toml.load(file)
return data
except FileNotFoundError:
print(f"Config `{file_path}` not found.")
sys.exit(1)
except toml.decoder.TomlDecodeError as e:
print(f"Error decoding config-file from `{file_path}`: {e}.")
sys.exit(1)
class LogFileHandler(FileSystemEventHandler):
def __init__(self, log_filename):
self.log_filename = log_filename
self.last_line_log = None
def on_modified(self, event):
if event.is_directory:
return
print(self.log_filename, event)
# определяем какие изменения произошли в файле
# elif event.event_type == 'modified' and event.src_path == self.log_filename:
# # Обработка изменений в лог-файле
# with open(event.src_path, 'r') as file:
# new_lines = file.readlines()
# # Обработка новых строк
# for line in new_lines:
# print(f"Изменение в {self.log_filename}:: {line}", end='')
2023-12-15 15:58:31 +03:00
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Проверка на запуск второго экземпляра
try:
me = SingleInstance(flavor_id="tacacs_watcher")
except SingleInstanceException:
print("Another instance is already running, quitting.")
sys.exit(1)
print(sys.platform, me.lockfile)
2023-12-15 15:58:31 +03:00
# Установка обработчика сигнала
signal.signal(signal.SIGTERM, handler_stop)
# Считывание имени config-файла их аргументов командной строки
try:
config_file = sys.argv[1] # первый аргумент после имени скрипта
except IndexError:
config_file = "tacacs_watcher.conf"
# Чтение файла конфигурации, приветствие и выставление интервала
config = read_toml(config_file)
if 'hello' in config:
print(config['hello'])
interval = config['interval'] if 'interval' in config else 1
# получаем все группы в конфиге
groups = [key for key, value in config.items() if isinstance(value, dict)]
observers = []
for group in groups:
if 'log_in' not in config[group]:
print(f"Config '{config_file}' not have key 'log_in' in group '{group}' (see config '{config_file}').")
continue
if not os.path.isfile(config[group]['log_in']):
print(f"File '{config[group]['log_in']}' not exist (see config '{config_file}').")
continue
if 'outdir' not in config[group]:
print(f"Config '{config_file}' not have key 'outdir' in group '{group}' (see config '{config_file}').")
continue
if not os.path.isdir(config[group]['outdir']):
print(f"Directory '{config[group]['outdir']}' not exist (see config '{config_file}').")
continue
observers.append(Observer())
observers[-1].schedule(LogFileHandler(config[group]['log_in']),
path=os.path.dirname(config[group]['log_in']),
recursive=False)
observers[-1].start()
# observer = Observer()
# event_handler = LogFileHandler(config[group]['log_in'])
# observer.schedule(event_handler, path=os.path.dirname(config[group]['log_in']), recursive=False)
if len(observers) == 0:
# если нет ни одной валидной группы, то выходим
print(f"Config '{config_file}' not have valid groups (see config '{config_file}').")
sys.exit(1)
2023-12-15 15:58:31 +03:00
# все обработчики в этом цикле
try:
while True:
# вечный цикл, чтобы программа не завершилась никогда (только принудительно или через SIGTERM)
print_hi('PyCharm')
time.sleep(interval)
except KeyboardInterrupt:
for observer in observers:
observer.stop()
2023-12-15 15:58:31 +03:00
print('Terminate by `KeyboardInterrupt`.')
sys.exit(0)
except ValueError:
print('Error value in config-file.')