Skip to content

Instantly share code, notes, and snippets.

@flexoid
Forked from himalay/auto-dns.sh
Last active February 23, 2021 09:47
Show Gist options
  • Save flexoid/fb2cc01b3ff3ac19659269a9c4c9ae2d to your computer and use it in GitHub Desktop.
Save flexoid/fb2cc01b3ff3ac19659269a9c4c9ae2d to your computer and use it in GitHub Desktop.
[Pi-hole auto DNS switch] The script automatically switches the DNS servers between Pi-hole and Cloudflare based on Pi-hole DNS Server status. #pihole #openwrt
#!/bin/sh
# The script automatically changed DNS servers advertised by DHCP based on Pi-hole DNS Server status.
# https://gist.github.com/flexoid/fb2cc01b3ff3ac19659269a9c4c9ae2d
TARGET=192.168.20.112 # Pi-hole
FALLBACK=8.8.8.8,8.8.4.4
function set_fallback_dns() {
echo $(date)
echo "Setting fallback DNS servers"
echo $FALLBACK
uci -q delete dhcp.lan.dhcp_option
uci add_list dhcp.lan.dhcp_option="6,$FALLBACK"
uci commit dhcp
/etc/init.d/dnsmasq restart
/etc/init.d/odhcpd restart
}
TARGET_PING_COUNT=$(ping -c 3 -w 3 $TARGET | grep seq | wc -l)
# check if pi is down
if [ $TARGET_PING_COUNT -eq 0 ]; then
FALLBACK_DNS_COUNT=$(uci show dhcp.lan.dhcp_option | grep $FALLBACK | wc -l)
# check if fallback is not set as a DNS server
if [ $FALLBACK_DNS_COUNT -eq 0 ]; then
set_fallback_dns
fi
else
TARGET_DNS_COUNT=$(uci show dhcp.lan.dhcp_option | grep $TARGET | wc -l)
# check if target is not set as a DNS server
if [ $TARGET_DNS_COUNT -eq 0 ]; then
TARGET_DNS_INFO_COUNT=$(dig +short @$TARGET TXT CHAOS version.bind | grep "pi-hole" | wc -l)
# check if pi-hole DNS is up
if [ $TARGET_DNS_INFO_COUNT -eq 1 ]; then
echo $(date)
echo "Setting target DNS server"
echo $TARGET
uci -q delete dhcp.lan.dhcp_option
uci add_list dhcp.lan.dhcp_option="6,$TARGET"
uci commit dhcp
/etc/init.d/dnsmasq restart
/etc/init.d/odhcpd restart
else
set_fallback_dns
fi
fi
fi

crontab

Edit configuration

crontab -e

The following job runs the /root/auto-dns.sh script every minute and appends the output to /root/cron.log file.

* * * * * /root/auto-dns.sh >> /root/cron.log 2>&1

Show configuration

crontab -l

Apply changes

/etc/init.d/cron restart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment