#!/bin/env python import os import time import subprocess import requests import sys from datetime import datetime # --- Configuration --- SERVER_TO_PING = "8.8.8.8" # Replace with the server you want to monitor FAIL_FILE = "ping_fail_timestamp.txt" # SEQ Logger Configuration SEQ_URL = "https://log.excaliburs-erben.de/ingest/clef" SEQ_API_KEY = "9SWjXUxmnzcgCKYfzXMI" # --------------------- def ping(host): """Returns True if host responds to a ping request.""" command = ['ping', '-c', '1', host] return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0 def sendSeqPayload(event): response = requests.post( SEQ_URL, json=event, headers={ "X-Seq-ApiKey": SEQ_API_KEY, "Content-Type": "application/vnd.serilog.clef", }, timeout=10 ) if response.status_code in (200, 201): print("Successfully logged to SEQ.") return True print(f"Failed to log to SEQ: HTTP {response.status_code} - {response.text}") return False def check_and_report_failure(): """Checks for the failure file on startup and logs to SEQ if found.""" if os.path.exists(FAIL_FILE): try: with open(FAIL_FILE, 'r') as f: fail_time = f.read().strip() print(f"Found failure record from: {fail_time}. Sending to SEQ...") event = { "@t": datetime.now().isoformat(), "@mt": "[{App}] Rebooted due to timeout at {FailTime}", "Level": "Information", "App": "Watchdog", "FailTime": fail_time } if sendSeqPayload(event): os.remove(FAIL_FILE) except Exception as e: print(f"Error handling the failure file or connecting to SEQ: {e}") def reset_wifi(): print(f"Network error detected. Resetting wlan0...") try: subprocess.run(["sudo", "nmcli", "radio", "wifi", "off"], check=True) time.sleep(2) # Give it a moment to completely power down the interface subprocess.run(["sudo", "nmcli", "radio", "wifi", "on"], check=True) print("WiFi reset command sent. Waiting for network to establish...") time.sleep(20) # Wait for DHCP and connection to re-establish event = { "@t": datetime.now().isoformat(), "@mt": "[{App}] Reset WiFi due to timeout", "Level": "Information", "App": "Watchdog" } sendSeqPayload(event) except subprocess.CalledProcessError as e: print(f"Failed to reset WiFi: {e}", file=sys.stderr) except Exception as e: print(f"Failed in reset Process: {e}", file=sys.stderr) def reboot_computer(): """Reboot the system and report any failure.""" result = subprocess.run(["/usr/sbin/reboot"], check=True) print(f"Reboot command exit code: {result.returncode}") if result.stdout: print(result.stdout) if result.stderr: print(result.stderr) return result.returncode == 0 def main(): check_and_report_failure() print(f"Starting connection monitor. Pinging {SERVER_TO_PING} every 10 seconds...") fail_count = 0 while True: if ping(SERVER_TO_PING): fail_count = 0 # Reset counter on success # print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping successful.") else: fail_count += 1 print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping failed. Consecutive failures: {fail_count}") if fail_count >= 3: reset_wifi() if fail_count >= 6: fail_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"Ping failed 3 times at {fail_time}. Writing fail-file and rebooting...") try: with open(FAIL_FILE, 'w') as f: f.write(fail_time) except IOError as e: print(f"Failed to write fail file: {e}") reboot_computer() break time.sleep(10) if __name__ == "__main__": main()