Dynamically arragne and check nameservers for resolv.conf

From Urandom
Jump to: navigation, search

I use this script to: 1) Remove any non working DNS servers from resolv.conf 2) Arrange the nameservers by ping time, so the faster ones would be primary.

Place the file to /opt/dnschecker/check_dns.sh

#!/bin/bash
DNS_SERVERS="10.180.1.165 10.180.131.200 10.180.131.253 10.180.1.253"  #List of available dns servers

TEST_HOST="loovsys.eu" #hostname to test
TEST_RESULT="10.180.1.226" #expected result


  RESOLV="/opt/dnschecker/resolv.temp"
  cat /etc/resolv.conf | grep -v "nameserver" > $RESOLV
  for server in $DNS_SERVERS
  do
    NSL=`nslookup $TEST_HOST $server | grep $TEST_RESULT`
    if [ $? -eq 0 ]
    then
      TIME=`ping $server -i 0.1 -c 3 -q -n | tail -1 | cut -d"/" -f5`
      echo "$TIME $server"
    fi
  done | sort | while read line
  do
    echo "nameserver `echo $line | cut -d' ' -f2`" >> $RESOLV
  done
  cat /etc/resolv.conf | grep nameserver | sort > $RESOLV.original
  cat $RESOLV | grep nameserver | sort > $RESOLV.new
  diff -q $RESOLV.new $RESOLV.original
  if [ $? -eq 1 ]
  then
    echo "`date +%Y-%m-%d_%H:%M:%S` Replacing resolv.conf with updated nameserver"
    mv $RESOLV /etc/resolv.conf
  fi



Personal tools