Skip to content

Instantly share code, notes, and snippets.

@user890104
Created October 21, 2017 19:36
Show Gist options
  • Save user890104/a9b097074669b78f451611320e472c2e to your computer and use it in GitHub Desktop.
Save user890104/a9b097074669b78f451611320e472c2e to your computer and use it in GitHub Desktop.
#!/bin/sh
ip_flip() {
if [ $1 -eq 4 ]
then
FIRST=$(echo $TUNNEL_IP | cut -d . -f 1-3).
LAST=$(echo $TUNNEL_IP | cut -d . -f 4)
fi
if [ $1 -eq 6 ]
then
FIRST=$(echo $TUNNEL_IP | awk -F: '{ for (i = 1; i < NF; i++) printf "%s:", $i }')
LAST=$(echo $TUNNEL_IP | awk -F: '{ print $NF }')
fi
if [ $((LAST % 2)) -eq 0 ]
then
LAST=$((LAST - 1))
else
LAST=$((LAST + 1))
fi
PEER_IP=${FIRST}${LAST}
}
ping_endpoint() {
# $1 NETIF_NAME
TAG='['$1']'
UCI_SECTION=network.${1}
PROTO="$(uci get ${UCI_SECTION}.proto)"
if [ $? -gt 0 ]
then
echo $TAG 'Interface not found!'
return 1
fi
PEER_IP="$(uci get ${UCI_SECTION}.peeraddr)"
if [ $? -gt 0 ]
then
echo $TAG 'Error getting interface IP!'
return 1
fi
echo $TAG Current IP: ${PEER_IP}
ping -c 1 -W 1 -q ${PEER_IP} > /dev/null
if [ $? -gt 0 ]
then
echo $TAG 'PING FAILED - Host is down!'
else
echo $TAG 'Host is up'
fi
if [ $PROTO = "6in4" ]
then
TUNNEL_IP="$(uci get ${UCI_SECTION}.ip6addr | cut -d / -f 1)"
ip_flip 6
fi
if [ $PROTO = "gre" ]
then
LINK_IF_NAME=l_${1:1}
TUNNEL_IP="$(uci get network.$LINK_IF_NAME.ipaddr)"
ip_flip 4
fi
if [ -n $PEER_IP ]
then
echo $TAG Peer IP: ${PEER_IP}
fi
ping -c 1 -W 1 -q ${PEER_IP} > /dev/null
if [ $? -gt 0 ]
then
echo $TAG 'PING FAILED - Host is down!'
else
echo $TAG 'Host is up'
fi
}
check_fix_ip() {
# $1 NETIF_NAME
# $2 HOSTNAME
TAG='['$1']'
echo $TAG Processing interface...
UCI_SECTION=network
UCI_KEY=${UCI_SECTION}.${1}.peeraddr
CURR_IP="$(uci get $UCI_KEY)"
if [ $? -gt 0 ]
then
echo 'Error getting interface IP!'
return 1
fi
echo $TAG Looking up hostname ${2}...
CORRECT_IP="$(nslookup $2 2> /dev/null | grep '^Address' | cut -d ' ' -f 3 | grep -vF ':')"
if [ "${CURR_IP}" = "${CORRECT_IP}" ]
then
echo $TAG IP ${CURR_IP} not changed
return 0
fi
echo $TAG IP changed: ${CURR_IP} '->' ${CORRECT_IP}, updating...
uci set "${UCI_KEY}=${CORRECT_IP}"
uci commit "${UCI_SECTION}"
ifdown $1
ifup $1
echo $TAG IP updated
}
# Examples
# check_fix_ip if_name hostname
# ping_endpoint if_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment