The following script allows you to detect dynamic ip changes and submit the changes to the NameCheap's DNS servers.


https://www.namecheap.com/support/knowledgebase/article.aspx/29/11/how-to-dynamically-update-the-hosts-ip-with-an-https-request/

NameCheap's DNS servers use dynamicdns.park-your-domain.com.


Features

  • allows multiple domain names to be updated
  • uses sendmail to send notifications on success/failure



#!/bin/bash

FORCE=false
ENABLE_SENDMAIL=true

TO="user@yahoo.com"
FROM=user@yahoo.com

HOSTNAME="@"
DOMAINS=(
          "site1.com"
          "site2.com"
)

PASSWORDS=(
            "key1"
            "key2"
)

BASE_URL="https://dynamicdns.park-your-domain.com/update"
TMP_FILE=/tmp/dyndns_mail.txt

EMAIL_BODY=""
LOG=""

function log(){
  echo $1
  LOG+="$1\n"
}

function sendNotification(){

  if [ $ENABLE_SENDMAIL == true ]; then
    SUBJECT="$1"

    echo "Subject: $SUBJECT" > $TMP_FILE
    echo "From: $FROM" >> $TMP_FILE
    echo "To: $TO" >> $TMP_FILE
    echo "" >> $TMP_FILE
    echo -e $LOG >> $TMP_FILE
    echo "" >> $TMP_FILE
    if [ -f ./site.output ]; then
      cat ./site.output >> $TMP_FILE
      rm ./site.output
    fi

    cat $TMP_FILE |sendmail -t
    rm $TMP_FILE
  fi
}

log "-- Dynamic Ip Address Updater --"
log " "

CURRENT_IP=$(curl -s 'https://api.ipify.org')
if [[ $CURRENT_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  log "CUR IP: $CURRENT_IP"
else
  log "--> Failed to determine current IP"
  sendNotification "Dynamic DNS Update Failure"
  exit
fi

DNS_IP=$(dig +short jmehan.com @resolver1.opendns.com)
if [[ $DNS_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  log "DNS IP: $DNS_IP"
  log " "
else
  log "--> Failed to determine DNS IP for ${DOMAINS[$index]}"
  sendNotification "Dynamic DNS Update Failure"
  exit 1
fi

NEEDS_UPDATING=false
FAILURE=false

log "Verifying Domain IPs"
for index in "${!DOMAINS[@]}"
do
    if [ "$DNS_IP" != "$CURRENT_IP" ] || [ $FORCE == true ]; then
      NEEDS_UPDATING=true
      URL="${BASE_URL}?host=$HOSTNAME&domain=${DOMAINS[$index]}&password=${PASSWORDS[$index]}"
      status_code=$(curl --write-out %{http_code} --silent --output site.output $URL)
      if [[ "$status_code" -ne 200 ]] ; then
        log "--> Error: StatusCode: $status_code"
        sendNotification "Dynamic DNS Update Failure"
        exit 1
      fi
      success=$(cat site.output |grep "<ErrCount>0</ErrCount>" |wc -l)
      if [[ "$success" -eq 1 ]] ; then
        log "- SUCCESS [ $DNS_IP -> $CURRENT_IP ] ${DOMAINS[$index]}"
      else
        FAILURE=true
        log "- FAILED  ${DOMAINS[$index]}"
        sendNotification "Dynamic DNS Update Failure"
      fi
    fi
done

if [ $NEEDS_UPDATING == true ]; then
  if [ $FAILURE == false ]; then
    log "Done"
    sendNotification "Dynamic DNS Updated"
  fi
else
   log "- Nothing to Update"
   log "Done"
fi
  • No labels