a picture my son drew of a wave on a beach

External IP

rbn

I keep meaning to put these scripts somewhere I can find them and then I don’t. So here, I am putting it here - and tagging the crap out of it. Stupid brain.

This script is basically how I automate finding and updating my external/WAN IP address. Easy.

I tidied up and expanded my previously apothegmatic code using ShellCheck. I wish something like that had been around twenty years ago when I was started breaking computers. If you are a learner use it for good bash scripting habits. If not, just give up like me.

Finding the IP address in this script uses opendns Vivek suggests some alternative methods


#!/bin/bash

# add this to a cronjob
# depends upon having dnsutils or dig installed.
# uses opendns to resolve external address [see ipcurrent]

# set values
src=$HOME"/bin/wanip.txt"
ipserv="[YOUR-SERVER]:/var/www/WAN-IP.txt"

# Check the source file exists
if [ ! -f "${src}" ]
then # if not create it
  echo "null" > "${src}"
fi

# Compare the old ip address in the source file to the current WAN ip address
ipold=$(cat "${src}")
ipcurrent="$(dig +short myip.opendns.com @resolver1.opendns.com)"

if [ "${ipcurrent}" != "${ipold}" ]; then
 echo "Old IP was \"${ipold}\", new IP is ${ipcurrent}"
 echo "${ipcurrent}" > "${src}" # update the source file
 scp "${src}" "${ipserv}"
else
 echo "external ip is: ${ipcurrent}"
 echo "on last change ip addr was copied to remote server:"
 echo "${src}" "${ipserv}"
 echo "no changes required - exiting not exciting."
fi

exit 0

Read or add a comment.
permalink