Write a python script to transfer the network to another interface in case if one interface is down
Here’s an updated Python script that continuously monitors the network connection on a primary interface, and if it goes down, switches to a backup interface.
Python Script:
import os
import subprocess
import time
PRIMARY_INTERFACE = "eth0" # Name of the primary network interface
SECONDARY_INTERFACE = "eth1" # Name of the secondary network interface
PING_HOST = "8.8.8.8" # Google's DNS server to check connectivity
CHECK_INTERVAL = 10 # Time interval between checks (in seconds)
def check_connectivity(interface):
"""Check if the given network interface has connectivity."""
try:
# Use ping to test connectivity on the specified interface
result = subprocess.run(
["ping", "-I", interface, "-c", "1", PING_HOST],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
return result.returncode == 0
except Exception as e:
print(f"Error checking connectivity on {interface}: {e}")
return False
def switch_interface(interface):
"""Bring the network interface up and make it the default route."""
try:
# Bring the interface up
print(f"Bringing up interface {interface}")
subprocess.run(["sudo", "ifconfig", interface, "up"], check=True)
# Remove default route
subprocess.run(["sudo", "ip", "route", "del", "default"], check=True)
# Set the default route to the new interface
subprocess.run(["sudo", "ip", "route", "add", "default", "dev", interface], check=True)
print(f"Switched to {interface} successfully!")
except Exception as e:
print(f"Failed to switch to {interface}: {e}")
def main():
using_secondary = False # Flag to track the current active interface
while True:
# Check connectivity on the primary interface
if check_connectivity(PRIMARY_INTERFACE):
if using_secondary:
print(f"Primary interface {PRIMARY_INTERFACE} is back. Switching back...")
switch_interface(PRIMARY_INTERFACE)
using_secondary = False
else:
print(f"Primary interface {PRIMARY_INTERFACE} is working fine.")
else:
print(f"Primary interface {PRIMARY_INTERFACE} is down.")
# If primary is down, switch to secondary
if not using_secondary:
print(f"Switching to secondary interface {SECONDARY_INTERFACE}...")
switch_interface(SECONDARY_INTERFACE)
using_secondary = True
# Wait for the next check
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
main()
Key Points:
1. check_connectivity(interface): This function checks if the given network interface has internet connectivity by pinging a remote server (8.8.8.8).
2. switch_interface(interface): This function brings up the interface and changes the default route to that interface, ensuring the system routes all traffic through it.
3. main():
It continuously monitors the primary interface (eth0) every few seconds (as defined by CHECK_INTERVAL).
If the primary interface is down, it switches to the secondary interface (eth1), bringing it up and setting the route.
When the primary interface comes back online, it switches back to it.
Requirements:
The script uses sudo to bring interfaces up and modify routes.
Interfaces must be available (eth0, eth1) on your system.
You can adjust the network interfaces, ping target, and check interval as necessary for your environment.
Python and Shell scripting Book: https://payhip.com/b/247HD

Comments
Post a Comment