Skip to content

Instantly share code, notes, and snippets.

@frennkie
Last active April 19, 2022 13:02
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 frennkie/6e5f6beaef1066f58df15c8cc8443b08 to your computer and use it in GitHub Desktop.
Save frennkie/6e5f6beaef1066f58df15c8cc8443b08 to your computer and use it in GitHub Desktop.
#!/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