Skip to content

Instantly share code, notes, and snippets.

@mahdi-malv
Forked from smhdhsn/configure_dns.sh
Created July 11, 2022 21:03
Show Gist options
  • Save mahdi-malv/80231201c608b6565916e7985ee50af8 to your computer and use it in GitHub Desktop.
Save mahdi-malv/80231201c608b6565916e7985ee50af8 to your computer and use it in GitHub Desktop.
Dynamic shecan.ir configurator.
#! /bin/bash
#####################################################
# Fetch DNS configurations from shecan.ir #
#####################################################
set -e
reset=`tput sgr0`
red=`tput setaf 1`
green=`tput setaf 2`
blue=`tput setaf 4`
# Prints out a success message.
function success { echo ${green}[+] ${1}${reset}; }
# Prints out a fail message.
function fail { echo ${red}[-] ${1}${reset}; }
# Prints out an info message.
function info { echo ${blue}[*] ${1}${reset}; }
# Default URL to get DNS configurations.
url='https://shecan.ir'
# Checks if a url is provided as the first input.
if [ ! -z $1 ]; then
url=$1
fi
# Default class name of the element.
hook='shecan-dns-ips'
# Checks if a hook is provided as the second input.
if [ ! -z $2 ]; then
hook=$2
fi
info "Fetching payload from '${url}'."
{
payload=$(curl -sX GET ${url}) &&
success "URL's payload has been cached."
} || {
fail "Error on caching URL's payload!"
}
# The RegEx pattern to get the configurations within payload.
extractConfig="(?<=class=\"${hook}\">).*?(?=<\/span>)"
info "Extracting configurations from payload."
{
configs=$(grep -Po ${extractConfig} <<< ${payload} 2> /dev/null) &&
success "DNS configurations has been extracted from payload."
} || {
fail "Error on extracting configurations from payload!"
}
# DNS's configuration key.
key="nameserver"
# path to DNS configurations.
filePath="/etc/resolv.conf"
# The RegEx pattern for IPv4.
ipv4RegEx=^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$
# Get line number of the first local DNS configuration.
first=$(grep -n ${key} ${filePath} | cut -f 1 -d ':' | head -n 1)
info "Editing '${filePath}'."
# Include fetched DNS configurations in DNS config file.
for config in $configs; do
if [[ $config =~ $ipv4RegEx ]]; then
sudo sed -i "${first}i\nameserver ${config}" $filePath
fi
done
success "Enjoy your freedom :)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment