Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Created December 4, 2023 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilangvperdana/76d3a13a89d9ab07fa94a334d4fbd63c to your computer and use it in GitHub Desktop.
Save gilangvperdana/76d3a13a89d9ab07fa94a334d4fbd63c to your computer and use it in GitHub Desktop.
Auto Change Default GW Ubuntu Script
#!/bin/bash
# List of gateways with corresponding interfaces
gateways=("192.168.100.1" "192.168.70.1" "192.168.80.1")
interfaces=("eth0" "eth1" "eth2")
# Function to check internet connectivity using a specific interface and gateway
check_gateway_connectivity() {
interface=$1
gateway=$2
ping -I $interface -c 1 -W 1 $gateway > /dev/null 2>&1
return $?
}
# Function to switch to a new gateway
switch_gateway() {
new_gateway=$1
new_interface=$2
# Delete existing default route
ip route del default
# Update default route to the new gateway
ip route replace default via $new_gateway dev $new_interface
echo "Switched to gateway $new_gateway via interface $new_interface"
}
# Loop through gateways
for ((i=0; i<${#gateways[@]}; i++)); do
gateway=${gateways[$i]}
interface=${interfaces[$i]}
# Check internet connectivity using the specific interface and gateway
check_gateway_connectivity $interface $gateway
if [ $? -eq 0 ]; then
# If gateway is reachable, update default route
switch_gateway $gateway $interface
exit 0
else
echo "Gateway $gateway via interface $interface not reachable. Trying next..."
fi
done
echo "No reachable gateway found."
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment