Shell – is it possible to check whether a local socks proxy works with shell script

shellsocks

Say I have a SOCKS connection at local (established by ssh -D8888). I use this to do many things, like bypass the internet censorship.

But sometimes the ssh would unexpectedly broken. Then the socks is down.

Is there anything that I can used to check whether the local SOCKS proxy is still alive?

Thanks,

Best Answer

You can test the availability of a socks proxy by trying to load a website through the tunnel.

curl -sSf --socks5-hostname localhost:8888 www.google.com > /dev/null

In the above command, curl will be silent, unless an error occurs. You can wrap this command in a for loop within a script. The return value of curl is zero if the socks proxy is alive (and google.com is not down).

#!/bin/bash

set -o errexit
set -o nounset
#set -o xtrace

PROGNAME=$(basename $0)
die () {
  echo "${PROGNAME}: ${1:-"Unknown Error, Abort."}" 1>&2
  exit 1
}

status=0
while [[ 1 ]]; do
  curl -sSf --socks5-hostname localhost:8888 www.google.com > /dev/null || status=$?
  if [[ $status -ne 0 ]]; then
    echo "Trying to reconnect .."
    # kill proxy
    # reconnect-cmd || die "$LINENO: reconnecting failed"
  fi
  sleep 100
done
Related Question