Auto-change proxy in Mac OS terminal per location

While almost all GUI tools on macOS respect the global proxy settings per Location, the terminal does not. As a developer switching between corporate and non-proxied networks, this is a big pain. Fortunately, I found a solution to automatically switch proxy settings when you change the Location setting in MacOS.

The above graphic shows two locations being defined on a Mac. One of them is called Office and uses the corporate proxy settings, the second one is called out of Office, not using any proxies.

When ever you change the location, the proxy settings will be taken over by GUI applications, but not for the terminal.

Very important for the “hack” we are using here is that the proxy settings are done correctly in the System Preferences -> Network -> Advanced -> Proxies section.

Above graphic shows the settings screen and you will notice, ONLY the HTTP and HTTPS Web Proxy settings are used. this is important, as the auto configuration from a script you might have set under Automatic Proxy Configuration will not work for our “hack”. If you do not have set the HTTP and HTTPS Web Proxy settings, you might need to investigate what your proxy IP actually is. Once you know it, please set it and the proxy port accordingly in the above screen.

Once everything is setup, Webbrowsers like Safari and Chrome should work well behind the corporate fire wall.

As the terminal does not natively support taking over the proxy settings, we will need to write a small script, which we will run on every terminal start.

Please paste the snippet below in your ~/.bash_profile file, to run it on each terminal start (if the file does not exist create it):

### Do the proxy setup
export http_proxy=`scutil --proxy | awk '\
  /HTTPEnable/ { enabled = $3; } \
  /HTTPProxy/ { server = $3; } \
  /HTTPPort/ { port = $3; } \
  END { if (enabled == "1") { print "http://" server ":" port; } }'`
export HTTP_PROXY="${http_proxy}"
export https_proxy=`scutil --proxy | awk '\
  /HTTPSEnable/ { enabled = $3; } \
  /HTTPSProxy/ { server = $3; } \
  /HTTPSPort/ { port = $3; } \
  END { if (enabled == "1") { print "https://" server ":" port; } }'`
export HTTPS_PROXY="${https_proxy}"

What it does is simple.. it uses scutil to read the HTTP and HTTPS variables from the config and exports them as environment variables if the settings exists.

When you now change your Location, these settings will change. Please restart your terminal or $ source ~/.bash_profile to let the changes take effect.

Thats it..

Leave a Reply

Copyright 2018
Tech Nerd theme designed by Siteturner