Skip to content

Instantly share code, notes, and snippets.

@frennkie
Last active Apr 19, 2022
Embed
What would you like to do?
#!/bin/bash
# don't use this if all your need is a route that goes through your ISP router
# instead of an openvpn tunnel. OpenVPN has this as a built-in feature!
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit 1
fi
TARGET="$1"
INTERFACE="$2"
LOG="/tmp/custom_route.log"
# for debugging
#set -x
# first check whether route exist already
if [[ $(ip route show ${TARGET} | wc -c) -ne 0 ]]; then
#echo "DBG: Route exists!"
echo "`date -Iseconds` Route to ${TARGET} via ${INTERFACE} exists already." >>${LOG}
exit 0 # all good
else
#echo "DBG: Route missing..."
# then find out the default gateway which must be via $INTERFACE
if [[ $(ip route show dev eth0 | grep default | cut -d" " -f3 | wc -c) -ne 0 ]]; then
GATEWAY=$(ip route show dev eth0 | grep default | cut -d" " -f3)
# echo "YEAH: now need to run: ip route add ${TARGET} via ${GATEWAY} dev ${INTERFACE} proto static"
echo "`date -Iseconds` Trying to add route to ${TARGET} via ${GATEWAY} on ${INTERFACE} now." >>${LOG}
ip route add ${TARGET} via ${GATEWAY} dev ${INTERFACE} proto static >/dev/null 2>&1
exit 0
else
#echo "DBG: else"
echo "`date -Iseconds` Unable to add route ${TARGET} via ${INTERFACE}!" >>${LOG}
exit 1
fi
fi
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment