Skip to content

Instantly share code, notes, and snippets.

@xirixiz
Last active November 13, 2021 07:28
Show Gist options
  • Save xirixiz/e5450381978402a5b888207d75c38c89 to your computer and use it in GitHub Desktop.
Save xirixiz/e5450381978402a5b888207d75c38c89 to your computer and use it in GitHub Desktop.
corporate proxy bash without cntlm

You can also make things static, like PROXY_USER, PROXY_SERVER, PROXY_PORT, but my advice is to never add the password. Ofcourse, when possible, you could also use CNTLM or CNTLM in Docker. However, I experienced that I couldn't use it always with CNTLM, hence this script, which I souce from ~/.bashrc

For the password you could also setup an ENV VAR called DOMAIN_PASSWORD. Long story short, I use it together with encrypted secrets to set this ENV VAR, but I didn't want to add it here :).

Usage: source ~/proxy.sh proxy_enable

#!/bin/bash

function __set_proxy_envs() {
    NO_PROXY_ENV="no_proxy NO_PROXY"
    PROXY_ENV="http_proxy ftp_proxy https_proxy rsync_proxy dns_proxy HTTP_PROXY HTTPS_PROXY FTP_PROXY RSYNC_PROXY DNS_PROXY"
}

function __unset_proxy_envs() {
    unset NO_PROXY_ENV PROXY_ENV
}

function proxy_enable() {
    __set_proxy_envs
    local NO_PROXY_VALUE='localhost,127.0.0.1'
    local PROXY_USER=''
    local PROXY_SERVER=''
    local PROXY_PORT='8080'
    if [ -z ${DOMAIN_PASSWORD} ]; then
      local PROXY_PASSWORD
    else
      PROXY_PASSWORD="${DOMAIN_PASSWORD}"
    fi

    if [[ -z "${PROXY_USER}" ]]; then
        echo -n "User: "; read PROXY_USER
    fi
    if [[ ! -z "${PROXY_USER}" ]] && [[ -z "${PROXY_PASSWORD}" ]]; then
        read -p "Password: " -s PROXY_PASSWORD &&  echo -e " "
    fi
    if [[ -z "${PROXY_SERVER}" ]]; then
        echo -n "Server: "; read PROXY_SERVER
    fi
    if [[ -z "${PROXY_PORT}" ]]; then
        echo -n "Port: "; read PROXY_PORT
    fi

    local PROXY_VALUE="http://${PROXY_USER}:${PROXY_PASSWORD}@${PROXY_SERVER}:${PROXY_PORT}"

    for envar in ${NO_PROXY_ENV}; do
        export $envar=${NO_PROXY_VALUE}
    done
    for envar in ${PROXY_ENV}; do
        export $envar=${PROXY_VALUE}
    done
    echo "No proxy value set to: ${NO_PROXY_VALUE}"
    echo "Proxy environment variable(s) set for: ${PROXY_ENV}"
    __unset_proxy_envs
}

function proxy_disable() {
    __set_proxy_envs
    for envar in ${PROXY_ENV} and ${NO_PROXY_ENV}; do
        unset $envar
    done
    echo "Proxy environment variable(s) removed: ${NO_PROXY_ENV} ${PROXY_ENV}"
    __unset_proxy_envs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment