I travel a lot, so I often connect to public Wi-Fi networks (on the train, for instance) but as a netadmin I also need to use very specific custom DNS servers at my day job (VPN, specific hostname resolutions, etc.). The thing is, when you have custom DNS configured, the DHCP-provided DNS servers aren’t used, so the Wi-Fi portal doesn’t show up. Conclusion: you can’t connect to the public Wi-Fi, and you’re mad at the train company until you figure out that you’re the problem.
So I created a simple script that I put in my .zshrc so I can easily see my current DNS (because I don’t want to go to the settings panel each time I need to change them), and update or remove them altogether if needed.
Here is the script:
dns() {
local SERVICE="${DNS_SERVICE:-Wi-Fi}"
case "$1" in
on)
sudo networksetup -setdnsservers "$SERVICE" 1.1.1.1 1.0.0.1 9.9.9.9
;;
google)
sudo networksetup -setdnsservers "$SERVICE" 8.8.8.8 8.8.4.4
;;
quad9)
sudo networksetup -setdnsservers "$SERVICE" 9.9.9.9 149.112.112.112
;;
off|auto)
sudo networksetup -setdnsservers "$SERVICE" empty
;;
show|status)
networksetup -getdnsservers "$SERVICE"
;;
list)
networksetup -listallnetworkservices
;;
service)
shift
export DNS_SERVICE="$*"
echo "DNS service set to: $DNS_SERVICE"
;;
*)
echo "Usage:"
echo " dns on # Cloudflare + Quad9"
echo " dns google # Google DNS"
echo " dns quad9 # Quad9 DNS"
echo " dns off # automatic DHCP DNS"
echo " dns show # current DNS"
echo " dns list # list services"
echo " dns service Wi-Fi"
;;
esac
}
And the usage is pretty self-explanatory:
Usage:
dns on # Cloudflare + Quad9
dns google # Google DNS
dns quad9 # Quad9 DNS
dns off # automatic DHCP DNS
dns show # current DNS
dns list # list services
dns service Wi-Fi
I’ve removed my custom DNS settings for this post, but the script is easy to update, so feel free to set your own DNS presets.
Don’t forget to run source ~/.zshrc to apply and test your changes after updating the file.