Skip to content

Instantly share code, notes, and snippets.

@himalay
Last active July 9, 2023 13:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save himalay/9b287f62bd4539e6db3996a4a8a3f72b to your computer and use it in GitHub Desktop.
Save himalay/9b287f62bd4539e6db3996a4a8a3f72b 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 switches the DNS servers between Pi-hole and Cloudflare based on Pi-hole DNS Server status.
TARGET=192.168.0.7 # Pi-hole
FALLBACK_A=1.1.1.1 # Cloudflare
FALLBACK_B=1.0.0.1 # Cloudflare
function set_fallback_dns() {
echo $(date)
echo "Setting fallback DNS servers"
echo $FALLBACK_A
echo $FALLBACK_B
uci -q delete dhcp.@dnsmasq[0].server
uci add_list dhcp.@dnsmasq[0].server=$FALLBACK_A
uci add_list dhcp.@dnsmasq[0].server=$FALLBACK_B
uci commit dhcp
/etc/init.d/dnsmasq 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.@dnsmasq[0].server | grep $FALLBACK_A | 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.@dnsmasq[0].server | 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.@dnsmasq[0].server
uci add_list dhcp.@dnsmasq[0].server=$TARGET
uci commit dhcp
/etc/init.d/dnsmasq 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

@CrAsH0v3r
Copy link

You juste saved me a couple of hours of work! Thanks a lot!

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