Skip to content

Instantly share code, notes, and snippets.

@arijusg
Created December 2, 2018 11:42
Show Gist options
  • Save arijusg/4582ae4ad3151eb4c1a64e2b9237fe29 to your computer and use it in GitHub Desktop.
Save arijusg/4582ae4ad3151eb4c1a64e2b9237fe29 to your computer and use it in GitHub Desktop.
Set proxy settings automatically using work laptop
#!/bin/bash
##########################################################################################
# Set proxy settings automatically using work laptop (~/.bashrc) #
##########################################################################################
USERNAME="<<username>> or <<domain\username>>"
PASSWORD="password"
PROXY_ADDRESS="proxy domain address"
NO_PROXY_DOMAINS=".local,.example.com"
WORK_IP_RANGE="10.10.10.*"
##########################################################################################
function encodeUrl() {
# encodeUrl <string>
old_lc_collate=$LC_COLLATE
LC_COLLATE=C
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%%%02X' "'$c" ;;
esac
done
LC_COLLATE=$old_lc_collate
}
function isWork() {
local IPs=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1')
local is_work=false
for ip in $(echo ${IPs} | tr " " "\n")
do
if [[ ${ip} == ${WORK_IP_RANGE} ]]; then
is_work=true
fi
done
echo "${is_work}"
}
function setWorkProxy() {
local PROXY_CREDENTIALS="$(encodeUrl ${USERNAME}):$(encodeUrl ${PASSWORD})"
local PROXY_ADDRESS_WITH_CREDENTIALS="http://${PROXY_CREDENTIALS}@${PROXY_ADDRESS}"
export http_proxy=$PROXY_ADDRESS_WITH_CREDENTIALS
export https_proxy=$http_proxy
export HTTP_PROXY=$http_proxy
export HTTPS_PROXY=$http_proxy
export no_proxy=${NO_PROXY_DOMAINS}
export NO_PROXY=$no_proxy
echo "==================== work proxy has been set ===================="
}
function unsetProxy() {
unset http_proxy
unset https_proxy
unset HTTP_PROXY
unset HTTPS_PROXY
unset no_proxy
unset NO_PROXY
}
function setProxy {
if [[ $(isWork) == true ]]; then
setWorkProxy
else
unsetProxy
fi
}
setProxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment