Skip to content

Instantly share code, notes, and snippets.

@theratman
Last active December 9, 2020 00:03
Show Gist options
  • Save theratman/52ec33315703ba5f994001409b3a3c05 to your computer and use it in GitHub Desktop.
Save theratman/52ec33315703ba5f994001409b3a3c05 to your computer and use it in GitHub Desktop.
DNS Switcher: Change DNS service on Mac OS X (use «dialog» that need to be installed before): brew install dialog)
#!/usr/bin/env zsh
IFS=$'\n'
#/ Usage: dnsswitcher.sh
#/ Description: Change DNS service on Mac OS X
#/ Examples: ./dnsswitcher.sh
#/ Options:
#/ --help: Display this help message
usage() { grep '^#/' "$0" | cut -c4- ; exit 0 ; }
expr "$*" : ".*--help" > /dev/null && usage
declare -A listDNS
listDNS[Google]="8.8.8.8 8.8.4.4"
listDNS[Cloudflare]="1.1.1.1 1.0.0.1"
listDNS[Quad9+DNSSEC+EDNS]="9.9.9.11 149.112.112.11"
declare -a Options
counter=0
for i in $(networksetup -listallnetworkservices | sed -n '1!p')
do
(( ++counter ))
Options+=( ${counter} "${i}")
done
Options=(${Options[@]})
cmd=(dialog --clear --backtitle "DNS Switcher" --title "[ M A I N - M E N U ]" --menu "Choose the interface:" 0 0 0 )
choices=$("${cmd[@]}" "${Options[@]}" 2>&1 >/dev/tty)
[[ -z ${choices} ]] && exit 1
((choice=2*$choices))
currentDNS=$(networksetup -getdnsservers ${Options[$choice]}|xargs)
declare -a tmpArray
for key value in ${(@kv)listDNS}; do
tmpArray+=( "${key}" "${value}")
done
tmpArray=(${tmpArray[@]})
cmd=(dialog --clear --backtitle "DNS Switcher" --title "Interface ${Options[$choice]}" --menu "Current DNS: ${currentDNS}" 0 0 0 )
choices=$("${cmd[@]}" "${tmpArray[@]}" 2>&1 >/dev/tty)
[[ -z ${choices} ]] && exit 1
echo -e \'${Options[$choice]}\' ${listDNS[$choices]} | xargs networksetup -setdnsservers
dialog --backtitle "DNS Switcher" --title "All done!" --infobox "DNS for the interface ${Options[$choice]} was changed to ${listDNS[$choices]}." 5 40
sleep 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment