Web proxy control for macOS

This script proxyctl helps control the Web Proxy preferences on macOS from the commandline.

I use proxyctl in aliases like:

# ~/.bashrc

alias mitmproxy.run='proxyctl start; mitmproxy -p 8888; proxyctl stop'

Now calling mitmproxy.run will configure and enable the system Web Proxy preferences, run mitmproxy, and after exiting mitmproxy will disable the Web Proxy preferences.

Here is the proxyctl script:

#!/bin/bash

# $ networksetup -listallnetworkservices
# An asterisk (*) denotes that a network service is disabled.
# Ethernet
# *Wi-Fi

domain=localhost
port=8888
networkservice=Ethernet
protocols="web secureweb"

#------------------------------------------------------------------------------

get_state() {
   for protocol in $protocols; do
      printf "\n%s:\n----------\n" "$protocol"
      networksetup "-get${protocol}proxy" "$networkservice"
   done
   echo
}

set_state() {
   for protocol in $protocols; do
      sudo networksetup "-set${protocol}proxystate" "$networkservice" "$1"
   done
}

set_domain_port() {
   for protocol in $protocols; do
      sudo networksetup "-set${protocol}proxy" "$networkservice" "$domain" "$port"
   done
}

is_enabled() {
   local res=0
   for protocol in $protocols; do
      if ! networksetup "-get${protocol}proxy" "$networkservice" | grep -q 'Enabled: Yes'; then
         (( res += 1 ))
      fi
   done
   return $res
}

set_enabled() {
   set_domain_port
   set_state on
   get_state
}

set_disabled() {
   set_state off
   get_state
}

case "$1" in
   start)
      set_enabled
      ;;
   stop)
      set_disabled
      ;;
   toggle)
      if is_enabled; then
         set_disabled
      else
         set_enabled
      fi
      ;;
   status)
      get_state
      ;;
   *)
      echo $"usage: ${0##*/} {start|stop|toggle|status}"
      exit 1
esac

download: proxyctl