Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Two ways of switching DNS via MikroTik script if PiHole fails.
# Mikrotik is set as DNS resolver (proxy).
# Changes upstream DNS config if PiHole fails.
# Tries to resolve google via pihole
# If it fails and DNS currently is pihole, sets fallback DNS as primary
# If it succeeds and DNS currently is not pihole, sets it as primary
# Notifies owner via his/her telegram bot
{
:local currentDNS [/ip dns get servers]
:local primaryDNS "192.168.1.5"
:local fallbackDNS "1.1.1.1,8.8.8.8"
# Telegram API stuff (https://stackoverflow.com/a/32572159)
:local chatID ""
:local botToken ""
:do {
:resolve google.com server=$primaryDNS
if ($currentDNS != $primaryDNS) do={
:log info "PiHole ($primaryDNS) back up"
/ip dns set servers=$primaryDNS
/tool fetch "https://api.telegram.org/bot$botToken/sendmessage\?chat_id=$chatID&text=Pi-Hole is back. Switching to $primaryDNS." keep-result=no
}
} on-error={
if ($currentDNS != $fallbackDNS) do={
:log warn "PiHole ($primaryDNS) down. Falling back to $fallbackDNS"
/ip dns set servers=$fallbackDNS
/tool fetch "https://api.telegram.org/bot$botToken/sendmessage\?chat_id=$chatID&text=Pi-Hole not working. Switching to $fallbackDNS." keep-result=no
}
}
}
# Changes DHCP DNS entry.
# Tries to resolve google via pihole
# If it fails and DNS currently is pihole, sets fallback DNS as primary
# If it succeeds and DNS currently is not pihole, sets it as primary
# Notifies owner via his/her telegram bot
{
:local currentDNS [/ip dhcp-server network get number=0 dns-server]
:local primaryDNS "192.168.1.5"
:local fallbackDNS "1.1.1.1,8.8.8.8"
# Telegram API stuff (https://stackoverflow.com/a/32572159)
:local chatID ""
:local botToken ""
:do {
:resolve google.com server=$primaryDNS
if ($currentDNS != $primaryDNS) do={
:log info "PiHole ($primaryDNS) back up"
/ip dhcp-server network set [find] dns-server=$primaryDNS
/tool fetch "https://api.telegram.org/bot$botToken/sendmessage\?chat_id=$chatID&text=Pi-Hole is back. Switching to $primaryDNS." keep-result=no
}
} on-error={
if ($currentDNS != $fallbackDNS) do={
:log warn "PiHole ($primaryDNS) down. Falling back to $fallbackDNS"
/ip dhcp-server network set [find] dns-server=$fallbackDNS
/tool fetch "https://api.telegram.org/bot$botToken/sendmessage\?chat_id=$chatID&text=Pi-Hole not working. Switching to $fallbackDNS." keep-result=no
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment