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
crontab -l
/etc/init.d/cron restart
| #!/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 |