DNS Switcher

Switch DNS to your defined DNS options.

Image preview of DNS Switcher plugin.

dnsswitcher.1d.sh

Edit
Open on GitHub
#!/usr/bin/env bash
#
# DNS Switcher
# The list of DNS options should be defined on this file
#
# <xbar.title>DNS Switcher</xbar.title>
# <xbar.version>v1.4</xbar.version>
# <xbar.author>M Saiqul Haq</xbar.author>
# <xbar.author.github>saiqulhaq</xbar.author.github>
# <xbar.desc>Switch DNS to your defined DNS options.</xbar.desc>
# <xbar.image>http://oi66.tinypic.com/2yplm4h.jpg</xbar.image>
# <xbar.abouturl>https://github.com/matryer/bitbar-plugins/blob/master/Network/dnsswitcher.1d.sh</xbar.abouturl>


# Configuration
# set your network service
network_service="Wi-FI"

# add or remove list of DNS options below, don't forget to make it enabled. see below
# shellcheck disable=2034
cloudflare="1.1.1.1
            1.0.0.1"

# shellcheck disable=2034
google="8.8.8.8
        8.8.4.4

        2001:4860:4860::8888
        2001:4860:4860::8844"

# shellcheck disable=2034
level3="209.244.0.3
        209.244.0.4

        4.2.2.1
        4.2.2.2

        4.2.2.3
        4.2.2.4"

# shellcheck disable=2034
opendns="208.67.222.222
        208.67.220.220"

# shellcheck disable=2034
norton="199.85.126.10
        199.85.127.10

        199.85.126.20
        199.85.127.20

        199.85.126.30
        199.85.127.30"

# shellcheck disable=2034
default="empty"

enabled_dns_address=(cloudflare google level3 opendns norton default)
########################


selected_dns="Unknown"
current_dns_output="$(networksetup -getdnsservers $network_service)"

if [[ $current_dns_output == There* ]] # For e.g. "There aren't any DNS Servers set on Wi-Fi."
then
    selected_dns="default"
else
    IFS=', ' read -r -a current_dns_address <<< "$current_dns_output"

    for dns_name in "${enabled_dns_address[@]}"
    do
        for current_dns in "${current_dns_address[@]}"
        do
        dns_option="$(eval echo \$"${dns_name}" | xargs)"
            if [[ $dns_option == *"$current_dns"* ]]
            then
                selected_dns="$dns_name"
            fi
        done
    done
fi


### Bitbar Menu
if [[ $selected_dns == "Unknown" ]]
then
    echo "Unrecognized DNS"
else
    echo "$selected_dns"
fi

echo "---"

tmp_dir="/tmp"
for dns_name in "${enabled_dns_address[@]}"
do
  switcher="$tmp_dir/bitbar_dns_switcher_${dns_name}"
  cat <<EOF > "$switcher"
dns_address='$(eval "echo \${${dns_name[*]}}")'
networksetup -setdnsservers $network_service \$(echo \$dns_address)
EOF
  chmod 700 "$switcher"
  echo "$dns_name | terminal=false refresh=true bash=$switcher"
done