Advertisement
VladyCu

Untitled

Apr 18th, 2025
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.26 KB | Source Code | 0 0
  1. import subprocess
  2. import time
  3. import os
  4. import sys
  5. import logging
  6.  
  7. # Configuration
  8. primary_gateway = "172.30.1.1"
  9. backup_gateway = "172.30.2.1"
  10. host_to_ping = "8.8.8.8"
  11. dhcp_config_file = "/etc/dnsmasq.d/02-pihole-dhcp.conf"  # Path to the DHCP config file
  12. dhcp_service_name = "pihole-FTL.service"
  13. ping_timeout = 3  # in seconds
  14. ping_interval = 10  # in seconds
  15. failure_threshold = 3  # Number of consecutive ping failures before switching
  16.  
  17. # Set up logging
  18. logging.basicConfig(filename='/var/log/gateway_failover.log', level=logging.INFO,
  19.                     format='%(asctime)s - %(message)s')
  20.  
  21. def log_message(message):
  22.     logging.info(message)
  23.  
  24. # Check for root privileges
  25. if os.geteuid() != 0:
  26.     print("This script requires root privileges.")
  27.     sys.exit(1)
  28.  
  29. def change_gateway(gateway):
  30.     """
  31.    Changes the default gateway for the server and updates the DHCP configuration
  32.    for all network clients.
  33.    """
  34.     try:
  35.         subprocess.run(["ip", "route", "del", "default"], check=True)
  36.         subprocess.run(["ip", "route", "add", "default", "via", gateway], check=True)
  37.         log_message(f"Server gateway changed to {gateway}")
  38.         update_dhcp_gateway(gateway)
  39.         restart_dhcp_server()
  40.     except subprocess.CalledProcessError as e:
  41.         log_message(f"Error changing gateway: {e}")
  42.  
  43. def update_dhcp_gateway(gateway):
  44.     """
  45.    Updates the DHCP configuration file to change the default gateway for clients.
  46.    """
  47.     try:
  48.         with open(dhcp_config_file, 'r') as file:
  49.             config = file.readlines()
  50.  
  51.         with open(dhcp_config_file, 'w') as file:
  52.             for line in config:
  53.                 if "dhcp-option=option:router" in line:
  54.                     file.write(f"dhcp-option=option:router,{gateway}\n")
  55.                 else:
  56.                     file.write(line)
  57.  
  58.         log_message(f"DHCP configuration updated with gateway {gateway}")
  59.     except Exception as e:
  60.         log_message(f"Error updating DHCP config: {e}")
  61.  
  62. def restart_dhcp_server():
  63.     """
  64.    Restarts the DHCP server to apply the new gateway settings to all clients.
  65.    """
  66.     try:
  67.         subprocess.run(["systemctl", "restart", dhcp_service_name], check=True)
  68.         log_message("DHCP server restarted successfully.")
  69.     except subprocess.CalledProcessError as e:
  70.         log_message(f"Error restarting DHCP server: {e}")
  71.  
  72. def ping_host_via_wlan(host):
  73.     """
  74.    Pings the specified host using the Raspberry Pi's wlan0 interface.
  75.    """
  76.     result = subprocess.run(
  77.         ["ping", "-I", "wlan0", "-c", "1", "-W", str(ping_timeout), host],
  78.         stdout=subprocess.DEVNULL
  79.     )
  80.     return result.returncode == 0
  81.  
  82. def ping_host(host):
  83.     """
  84.    Pings the specified host via current default interface.
  85.    """
  86.     result = subprocess.run(
  87.         ["ping", "-c", "1", "-W", str(ping_timeout), host],
  88.         stdout=subprocess.DEVNULL
  89.     )
  90.     return result.returncode == 0
  91.  
  92. def main():
  93.     current_gateway = primary_gateway
  94.     consecutive_failures = 0
  95.     wlan_successes = 0
  96.  
  97.     try:
  98.         while True:
  99.             if current_gateway == primary_gateway:
  100.                 if ping_host(host_to_ping):
  101.                     consecutive_failures = 0
  102.                 else:
  103.                     consecutive_failures += 1
  104.                     if consecutive_failures >= failure_threshold:
  105.                         change_gateway(backup_gateway)
  106.                         current_gateway = backup_gateway
  107.                         log_message("Switched to backup gateway.")
  108.                         wlan_successes = 0  # reset counter for recovery
  109.             else:
  110.                 # On backup, check if we can reach via wlan0
  111.                 if ping_host_via_wlan(host_to_ping):
  112.                     wlan_successes += 1
  113.                     if wlan_successes >= 3:
  114.                         change_gateway(primary_gateway)
  115.                         current_gateway = primary_gateway
  116.                         log_message("Switched back to primary gateway.")
  117.                         consecutive_failures = 0
  118.                 else:
  119.                     wlan_successes = 0
  120.  
  121.             time.sleep(ping_interval)
  122.  
  123.     except KeyboardInterrupt:
  124.         log_message("Script terminated by user.")
  125.  
  126. if __name__ == "__main__":
  127.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement