Skip to content

Instantly share code, notes, and snippets.

@nash403
Last active April 29, 2024 04:59
Show Gist options
  • Save nash403/5878e4f6e0dbe832a37a6c8cefc545c9 to your computer and use it in GitHub Desktop.
Save nash403/5878e4f6e0dbe832a37a6c8cefc545c9 to your computer and use it in GitHub Desktop.
Automatically enable/disable proxy settings from command line
# Show proxy settings
function proxy_show(){
env | grep -e _PROXY -e _proxy | sort
}
# Configure proxy
function proxy_on(){
# You may need to hardcode your password, proxy server, and proxy port
# if the following variables do not exist
export HTTP_PROXY="http://$USERNAME:$PASSWORD@$PROXY_SERVER:$PROXY_PORT"
export HTTPS_PROXY=$HTTP_PROXY
export FTP_PROXY=$HTTP_PROXY
export http_proxy=$HTTP_PROXY
export https_proxy=$HTTP_PROXY
export ftp_proxy=$HTTP_PROXY
# export SOCKS_PROXY=$HTTP_PROXY
# export no_proxy="localhost,127.0.0.1,$USERDNSDOMAIN"
export no_proxy="localhost,127.0.0.0/8,::1"
# Update git and npm to use the proxy
if hash git 2>/dev/null; then
git config --global http.proxy $HTTP_PROXY
git config --global https.proxy $HTTP_PROXY
fi
if hash npm 2>/dev/null; then
npm config set proxy $HTTP_PROXY
npm config set https-proxy $HTTP_PROXY
# npm config set strict-ssl false
# npm config set registry "http://registry.npmjs.org/"
fi
proxy_show
echo -e "\nProxy-related environment variables set."
# clear
}
# Enable proxy settings immediately
# proxy_on
# Disable proxy settings
function proxy_off(){
variables=( \
"HTTP_PROXY" "HTTPS_PROXY" "FTP_PROXY" \
"no_proxy" "http_proxy" "https_proxy" "ftp_proxy" \
)
for i in "${variables[@]}"
do
unset $i
done
# Update git and npm to disable the proxy
if hash git 2>/dev/null; then
git config --global --unset http.proxy
git config --global --unset https.proxy
fi
if hash npm 2>/dev/null; then
npm config rm proxy
npm config rm https-proxy
# npm config set strict-ssl false
# npm config set registry "http://registry.npmjs.org/"
fi
proxy_show
echo -e "\nProxy-related environment variables removed."
}

At any time you can type proxy_on/proxy_off to enable/disable proxy.

You may need to hardcode your password, proxy server, and proxy port on line 11. Just replace each $VAR_NAME with the actual value.

Put this file in your home directory. Make sure the file is called .bashrc. Append this to the file if it already exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment