codenamev
9/18/2013 - 12:06 PM

Creates an SSH tunnel and sets up a SOCKS proxy on your OSX machine

Creates an SSH tunnel and sets up a SOCKS proxy on your OSX machine

#!/bin/bash

# Include this file in your .zshrc or .bashrc, or just add this function directly to it
#
# Usage:
#   > proxify
#   # prompts you for your ssh password
#   # OSX may prompt you to confirm the changes to your network settings
#
# Once complete, you will have an SSH tunnel established to your remote host
# and your network settings will be updated to forward your internet traffic
# through the SSH tunnel using a SOCKS proxy
function proxify()
{
  SSH_HOST="replace.with.your.host.name.com"
  SSH_USER="replace.with.ssh.user"
  SSH_PORT=21 #change if you use a custom ssh port
  SOCKS_PROXY_HOST=localhost
  SOCKS_PROXY_PORT=8080
  NW_SERVICE=Wi-Fi # /usr/sbin/networksetup -listallnetworkservices

  # DO NOT CHANGE
  NWSETUP_CMD="networksetup"
  SSH_CMD="/usr/bin/ssh -D $SOCKS_PROXY_PORT -p $SSH_PORT -Nf $SSH_USER@$SSH_HOST"

  SOCKS_PROXY_ENABLED=
  if $NWSETUP_CMD -getsocksfirewallproxy $NW_SERVICE | grep -q "^Enabled: Yes"; then
      SOCKS_PROXY_ENABLED=1
  fi
  SSH_PID=`pgrep -f "$SSH_CMD"`

  enable_socks_proxy() {
      echo Enable SOCKS Firewall Proxy.
      $NWSETUP_CMD -setsocksfirewallproxy $NW_SERVICE $SOCKS_PROXY_HOST $SOCKS_PROXY_PORT off
  }

  disable_socks_proxy() {
      if [ $SOCKS_PROXY_ENABLED ]; then
    echo Disable SOCKS Firewall Proxy.
    $NWSETUP_CMD -setsocksfirewallproxystate $NW_SERVICE off
      fi
  }

  create_ssh_connection() {
    echo Create SSH Connection to $SSH_HOST.
    eval $SSH_CMD
  }

  destroy_ssh_connection() {
    if [ $SSH_PID ]; then
      echo Destroy SSH Connection to $SSH_HOST.
      kill -TERM $SSH_PID
    fi
  }

  case $1 in
    start)
      destroy_ssh_connection
      create_ssh_connection
      enable_socks_proxy
      ;;
    stop)
      disable_socks_proxy
      destroy_ssh_connection
      ;;
    pid)
      if [ $SSH_PID ]; then
          echo $SSH_PID
      else
          echo SSH Connection to $SSH_HOST is dead.
      fi
      ;;
    status)
      if [ $SSH_PID ]; then
        echo SSH Connection to $SSH_HOST is alive \(PID:$SSH_PID\).
      else
        echo SSH Connection to $SSH_HOST is dead.
      fi
      if [ $SOCKS_PROXY_ENABLED ]; then
        echo SOCKS Firewall Proxy is on.
      else
        echo SOCKS Firewall Proxy is off.
      fi
      ;;
    on)
      enable_socks_proxy
      ;;
    off)
      disable_socks_proxy
      ;;
    toggle)
      if [ $SOCKS_PROXY_ENABLED ]; then
        disable_socks_proxy
      else
        enable_socks_proxy
      fi
      ;;
    *)
      echo "Usage: $0 {start|stop|status|on|off|toggle|help}"
      #exit 1
      ;;
  esac

  #exit 0
}