how to you toggle on and off a web proxy in os x from the command line

Viewed 24452

In OS X, you turn on and off a web proxy from System Preferences > Network > Proxies, by checking Web Proxy (HTTP) and designating the Web Proxy Server etc. and by clicking OK and then "Apply". This is way too many steps. Is there a way to do this all from the command line and a shell script?

7 Answers

Enabling and Disabling Proxy with a keyboard shortcut

In terminal, you can turn wifi proxy off and on with these commands

networksetup -setwebproxystate Wi-Fi <on | off>
networksetup -setsecurewebproxystate Wi-Fi <on | off>

and Ethernet

networksetup -setwebproxystate Ethernet <on | off>
networksetup -setsecurewebproxystate Ethernet <on | off>

Here's a one-liner to toggle between on and off (Using Wi-Fi example)

e=$(networksetup -getwebproxy wi-fi | grep "No")

if [ -n "$e" ]; then
  networksetup -setwebproxystate  Wi-Fi on
  networksetup -setsecurewebproxystate  Wi-Fi on
else
  networksetup -setwebproxystate  Wi-Fi off
  networksetup -setsecurewebproxystate  Wi-Fi off
fi

Create a keyboard shortcut that runs a shell command

  1. Start Automator, and create a new Service.

  2. Set "Service receives selected: to "no input" in "any application".

  3. Add an action named "Run Shell Script". It's in the Utilities section of the Actions Library.

  4. Insert the bash command you want into the text box and test run it using the Run button (top right). It should do whatever the script does (off, on or toggle), and there should be green ticks below the Action.

  5. Save it, giving it a service name you can remember.

  6. Go to System Preferences -> Keyboard, and go to the Shortcuts tab

  7. Go to the Services section, and scroll down to General - you should find your service there. If you select the line, you can click "add shortcut" and give it a keyboard shortcut.

As I needed a simple script that will just toggle both HTTP and HTTPS proxies on/off at the same time, here it is:

#!/usr/bin/env bash
# Toggles *both* HTTP and HTTP proxy for a preconfigured service name ("Wi-Fi" or "Ethernet").

NETWORK_SERVICE_NAME="Wi-Fi" # Wi-Fi | Ethernet

IS_PROXY_ENABLED=$(networksetup -getwebproxy "$NETWORK_SERVICE_NAME" | head -n 1 | grep Yes)

if [ -z "$IS_PROXY_ENABLED" ]; then
    echo "Enabling HTTP and HTTPs proxy for $NETWORK_SERVICE_NAME"
    networksetup -setstreamingproxystate "$NETWORK_SERVICE_NAME" on
    networksetup -setwebproxystate "$NETWORK_SERVICE_NAME" on
    networksetup -setsecurewebproxystate "$NETWORK_SERVICE_NAME" on
else
    echo "Disabling HTTP and HTTPs proxy for $NETWORK_SERVICE_NAME"
    networksetup -setstreamingproxystate "$NETWORK_SERVICE_NAME" off
    networksetup -setwebproxystate "$NETWORK_SERVICE_NAME" off
    networksetup -setsecurewebproxystate "$NETWORK_SERVICE_NAME" off
fi
Related