Skip to content

Instantly share code, notes, and snippets.

@ntrepid8
Created April 7, 2017 00:19
Show Gist options
  • Save ntrepid8/49177f114b082df25c670a5f469c06d1 to your computer and use it in GitHub Desktop.
Save ntrepid8/49177f114b082df25c670a5f469c06d1 to your computer and use it in GitHub Desktop.
Script to create static routes for individual host names and network interfaces
#!/usr/bin/env bash
# Create a static route for a given host/domain over a specific network interface.
# Put this script in /etc/network/if-up.d/host-interface-route so it runs when the interface comes up
# Script was developer for Ubuntu 16.04 LTS running Network Manager (Gnome 3)
# I use this script to prevent my VPN connections from interfering with automatic reverse SSH tunnles
# to my jump box running in the cloud.
# network interface to target
TARGET_IFACE="eth0"
# hostname to target
TARGET_HOST="jump.your-host-here.io"
# metric (lower number is higher priority)
# useful if you have more than one interface such as a wired Ethernet and a wifi radio
METRIC=50
if [ "${IFACE}" == "${TARGET_IFACE}" ]; then
# resolve the hostname to an IP address
DST_IP=$(dig +short "${TARGET_HOST}")
# determine the gateway for our interface and IP
GATEWAY=$(ip route get "${DST_IP}" oif "${IFACE}" | awk "/${IFACE}/ { print \$3 }")
# add the static route
ip route add "${DST_IP}" via "${GATEWAY}" dev "${IFACE}" metric "${METRIC}"
fi