Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import subprocess
- import time
- import os
- import sys
- import logging
- # Configuration
- primary_gateway = "172.30.1.1"
- backup_gateway = "172.30.2.1"
- host_to_ping = "8.8.8.8"
- dhcp_config_file = "/etc/dnsmasq.d/02-pihole-dhcp.conf" # Path to the DHCP config file
- dhcp_service_name = "pihole-FTL.service"
- ping_timeout = 3 # in seconds
- ping_interval = 10 # in seconds
- failure_threshold = 3 # Number of consecutive ping failures before switching
- # Set up logging
- logging.basicConfig(filename='/var/log/gateway_failover.log', level=logging.INFO,
- format='%(asctime)s - %(message)s')
- def log_message(message):
- logging.info(message)
- # Check for root privileges
- if os.geteuid() != 0:
- print("This script requires root privileges.")
- sys.exit(1)
- def change_gateway(gateway):
- """
- Changes the default gateway for the server and updates the DHCP configuration
- for all network clients.
- """
- try:
- subprocess.run(["ip", "route", "del", "default"], check=True)
- subprocess.run(["ip", "route", "add", "default", "via", gateway], check=True)
- log_message(f"Server gateway changed to {gateway}")
- update_dhcp_gateway(gateway)
- restart_dhcp_server()
- except subprocess.CalledProcessError as e:
- log_message(f"Error changing gateway: {e}")
- def update_dhcp_gateway(gateway):
- """
- Updates the DHCP configuration file to change the default gateway for clients.
- """
- try:
- with open(dhcp_config_file, 'r') as file:
- config = file.readlines()
- with open(dhcp_config_file, 'w') as file:
- for line in config:
- if "dhcp-option=option:router" in line:
- file.write(f"dhcp-option=option:router,{gateway}\n")
- else:
- file.write(line)
- log_message(f"DHCP configuration updated with gateway {gateway}")
- except Exception as e:
- log_message(f"Error updating DHCP config: {e}")
- def restart_dhcp_server():
- """
- Restarts the DHCP server to apply the new gateway settings to all clients.
- """
- try:
- subprocess.run(["systemctl", "restart", dhcp_service_name], check=True)
- log_message("DHCP server restarted successfully.")
- except subprocess.CalledProcessError as e:
- log_message(f"Error restarting DHCP server: {e}")
- def ping_host_via_wlan(host):
- """
- Pings the specified host using the Raspberry Pi's wlan0 interface.
- """
- result = subprocess.run(
- ["ping", "-I", "wlan0", "-c", "1", "-W", str(ping_timeout), host],
- stdout=subprocess.DEVNULL
- )
- return result.returncode == 0
- def ping_host(host):
- """
- Pings the specified host via current default interface.
- """
- result = subprocess.run(
- ["ping", "-c", "1", "-W", str(ping_timeout), host],
- stdout=subprocess.DEVNULL
- )
- return result.returncode == 0
- def main():
- current_gateway = primary_gateway
- consecutive_failures = 0
- wlan_successes = 0
- try:
- while True:
- if current_gateway == primary_gateway:
- if ping_host(host_to_ping):
- consecutive_failures = 0
- else:
- consecutive_failures += 1
- if consecutive_failures >= failure_threshold:
- change_gateway(backup_gateway)
- current_gateway = backup_gateway
- log_message("Switched to backup gateway.")
- wlan_successes = 0 # reset counter for recovery
- else:
- # On backup, check if we can reach via wlan0
- if ping_host_via_wlan(host_to_ping):
- wlan_successes += 1
- if wlan_successes >= 3:
- change_gateway(primary_gateway)
- current_gateway = primary_gateway
- log_message("Switched back to primary gateway.")
- consecutive_failures = 0
- else:
- wlan_successes = 0
- time.sleep(ping_interval)
- except KeyboardInterrupt:
- log_message("Script terminated by user.")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement