Skip to content

Instantly share code, notes, and snippets.

@laacz
Last active June 13, 2023 18:13
Show Gist options
  • Save laacz/9b79a3214c3272d8ca857dcd117fdb9f to your computer and use it in GitHub Desktop.
Save laacz/9b79a3214c3272d8ca857dcd117fdb9f to your computer and use it in GitHub Desktop.
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