Created
June 2, 2021 23:49
-
-
Save marcolarosa/e95df344552ea10a31775ea7f81e2c12 to your computer and use it in GitHub Desktop.
Fix split routing table on linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
is_private_network() { | |
NETWORK=${1} | |
is_private=0 | |
for i in $(seq 0 255); do | |
match=$(echo $NETWORK | grep "10.$i") | |
[[ ! -z $match ]] && is_private=1 | |
done | |
for i in $(seq 16 31); do | |
match=$(echo $NETWORK | grep "172.$i") | |
[[ ! -z $match ]] && is_private=1 | |
done | |
match=$(echo $NETWORK | grep "192.168") | |
[[ ! -z $match ]] && is_private=1 | |
echo $is_private | |
} | |
INTERFACES=$(ip a s | grep -E "inet.*eth" | awk '{print $8}') | |
# is there only one interface - do nothing | |
if [ $(echo $INTERFACES | wc -w) == 1 ] ; then | |
echo "Only one interface attached to this host so nothing to do" | |
exit 0 | |
fi | |
# check each interface and remove default routes to private networks | |
for int in $INTERFACES; do | |
INTERFACE_IP=$(ip a s | grep -E "inet.*${int}" | awk '{print $2}' | awk -F '.' '{print $1"."$2}') | |
IS_PRIVATE_NETWORK=$(is_private_network $INTERFACE_IP) | |
if [ $IS_PRIVATE_NETWORK == 1 ] ; then | |
# looks like a private network so remove default route if any | |
ROUTE=$(route | grep $INTERFACE_IP | grep default) | |
if [ ! -z "$ROUTE" ] ; then | |
NET=$(echo $ROUTE | awk '{print $3}') | |
GW=$(echo $ROUTE | awk '{print $2}') | |
route del -net $NET gw $GW | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had an issue recently where my VMS were coming up with two default routes - one public and one private. After a long and frustrating thread with the support people on auto fixing this I decided to write it myself.
The idea is that it looks for default routes to private networks and removes them when there is more than one network interface. It assumes that public interfaces have resulted in default routes being setup. It won't handle multiple default routes to public networks though I'm sure you could adapt easily to choose one. It makes no other changes to the route table and only requires, bash, grep and awk.
Route table before with two default routes - one private, one public
Route table after: