Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update configuration file based on dynamic ip address
#!/bin/bash
#
# 2017-04-27
# myrveln@gmail.com
#
# Update IPsec dynamic ip address
#
DOMAIN_CHECK="myrveln.se"
CONFIG_FILE="/etc/ipsec.conf"
LOGFILE="/var/log/vpn-ip-update.log"
# Function to validate an ip address
function ValidateIp()
{
local IP=$1
local RETURN_CODE=1
if [[ $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
IP=($IP)
IFS=$OIFS
[[ ${IP[0]} -le 255 && ${IP[1]} -le 255 \
&& ${IP[2]} -le 255 && ${IP[3]} -le 255 ]]
RETURN_CODE=$?
fi
return $RETURN_CODE
}
# Get the configured ip address, and the real ip
IP_CONFIG="$(grep 'leftid=' ${CONFIG_FILE} | cut -d'=' -f2)"
IP_REAL="$(curl -s -S ifconfig.co)"
# Validate the ip's
ValidateIp ${IP_CONFIG}
RETURN_CURRENT=$?
ValidateIp ${IP_REAL}
RETURN_DNS=$?
# If either of the ip's are invalid, break the script.
# Retrieving the ip's have probably failed.
if [[ ! ${RETURN_CURRENT} -eq 0 ]] || [[ ! ${RETURN_DNS} -eq 0 ]]; then exit 1; fi
# Check whether the ip's differs
if [[ ${IP_CONFIG} != ${IP_REAL} ]]; then
# Sed IPsec config file and create backup if verify fails
sed -i.bak "s/leftid=.*/leftid=${IP_REAL}/g" ${CONFIG_FILE}
# Verifying the new IPsec config
IPSEC_VERIFY=$(/usr/bin/ipsec verify 2> /dev/null)
RETURN=$?
if [[ ${RETURN} -eq 0 ]]; then
# Verify is OK, restart IPsec service
echo "$(date +%F): [INFO] Changed IP from ${IP_CONFIG} to ${IP_REAL}" >> ${LOGFILE}
rm ${CONFIG_FILE}.bak
/usr/bin/systemctl restart ipsec
else
echo "$(date +%F): [ERROR] Verification of ${CONFIG_FILE} failed. Restoring config from backup!" >> ${LOGFILE}
mv ${CONFIG_FILE}.bak ${CONFIG_FILE}
exit 1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.