ChangeGateway.sh Cambia tu puerta de enlace a otra que tengas en tu red. exDebian

ChangeGateway.sh Cambia tu puerta de enlace a otra que tengas en tu red.

Solapas principales

Nombre: ChangeGateway.sh
Autor: NerveNet
Origen: Original
Lenguaje: BASH
Licencia: GPL
Propósito: Cambia la puerta de enlace que por defecto tengamos configurada por otra que hayamos definido en el script (variable NEWGATEWAY) y viceversa.
Dependencias: tener instalado Bash, grep, awk, head, ip (paquete iproute2)
 

Código:

#!/bin/bash
# by NerveNet 2019
# Set the default gateway depending on the default gateway that is set
# Script asumes that only one route for the default gateway exist
# The following two variables contain the two gateways available on the network
DEFAULTGATEWAY="172.26.0.1"
NEWGATEWAY="172.26.0.2"
# Now we get all needed information
CURRENTDEFAULT="$(ip route | grep default | head -n 1)"
CURRENTGATEWAY="$(echo $CURRENTDEFAULT | awk '{print $3}')"
DELROUTECMD="ip route del default via ${CURRENTGATEWAY}"
SETROUTECMD="ip route add default via "
# Now I check the gateway used and do the corresponding changes or exit with a warning
if [ $CURRENTGATEWAY = $DEFAULTGATEWAY ]; then
	SETROUTECMD+="${NEWGATEWAY}"
elif [ $CURRENTGATEWAY = $NEWGATEWAY ]; then
	SETROUTECMD+="${DEFAULTGATEWAY}"
else
	echo "No valid gateway found! No changes done."
	exit 1
fi
# Adding proto & metric information if available
if [ "$(echo $CURRENTDEFAULT | awk '{print $6}')" = "proto" ]; then
	SETROUTECMD+=" proto $(echo $CURRENTDEFAULT | awk '{print $7}')"
elif [ "$(echo $CURRENTDEFAULT | awk '{print $6}')" = "onlink" ]; then
	SETROUTECMD+=" onlink"
fi
if [ "$(echo $CURRENTDEFAULT | awk '{print $8}')" = "metric" ]; then
	SETROUTECMD+=" metric $(echo $CURRENTDEFAULT | awk '{print $9}')"
fi
# We print the current default route 
echo -en "Changing default gateway\nCurrent route:\t"
echo $CURRENTDEFAULT | awk '{print $1, $2, $3, $6, $7, $8, $9}'
# Deleting and setting the default route
eval $DELROUTECMD
eval $SETROUTECMD
# We print the new default route 
echo -en "New route:\t"
ip route | grep default | awk '{print $1, $2, $3, $6, $7, $8, $9}'
exit

 

Ejemplos de uso: Pongamos que tienes una red en la que tienes dos routers y que quieres usar uno u otro router cambiando la puerta de enlace por defecto.
Este script hace el trabajo por ti, comprueba cual es la puerta de enlace que tienes configurada y cambia la configuración para apuntar a la otra.

Comentarios: Para que el script funcione correctamente debes editarlo y cambiar los valores de las variables DEFAULTGATEWAY y NEWGATEWAY a los que tengas configurados en tu red.
El script presupone que sólo hay una puerta de enlace configurada. Sólo cambiará la primera que encuentre.