Archive for December, 2009

Bash: Auto-Detecting a http proxy

This bash function detects a http proxy. It tries the current http_proxy environment variable, direct connection, firefox settings and simple automatic proxy configuration (wpad).

Use it like this:

export http_proxy=$(detectProxy)

function detectProxy() {
URL=http://www.google.co.uk/
wget -q -O /dev/null $URL && echo $http_proxy && return
unset http_proxy
wget -q --no-proxy -O /dev/null $URL && return

for i in ~/.mozilla/*/*/prefs.js
do
host=$(grep -Eo ‘network.proxy.http”, “[^"]*’ $i | sed ’s/.*, “//g’)
port=$(grep -Eo ‘network.proxy.http_port”, [^)]*’ $i | sed ’s/.*, //g’)
if [ -z "$host" ] || [ -z "$port" ]; then
continue
fi
export http_proxy=http://$host:$port/
wget -q -O /dev/null $URL && echo $http_proxy && return
done
export http_proxy=http://$(wget -q wpad/wpad.dat -O – |
grep -Eo ‘return [^;]*’| sed ’s,return ,,g’|sed “s,['\"]*,,g”)
wget -q -O /dev/null $URL && echo $http_proxy && return
unset http_proxy
echo unable to detect proxy >&2
}

2 Comments