How to script Network Preferences using the CLI

As the title implies for development I enable/disable Web proxies, however doing it through the UI is slow and cumbersome its also pretty inflexible.

I'm looking to control the following checked settings:

Advanced Network Settings

I tried using the following script to identify any changes but it did not work:

defaults read > current-defaults.txt

# Do change in UI and then run the following:
defaults read > changed-defaults.txt

diff current-defaults.txt changed-defaults.txt

This answer has information but is not as specific to solve solve my needs


Try networksetup ... From man networksetup .. NOTE must be an admin to run it.

DESCRIPTION The networksetup command is used to configure network settings typically configured in the System Preferences application. The networksetup command requires at least admin privileges to change network settings. If the "Require an administrator password to access system-wide preferences" option is selected in System Preferences > Security & Privacy, then root privileges are required to change network settings.

You can make changes to many OSX network settings using similar tools to linux platforms, using networksetup ensures everything running is properly informed, settings are saved, and upon reboot those saved values are still usable (exactly as if you had used System Preferences) - see this answer to another networking questions that talks about how that works.

The basic reason is that macOS has two different levels of network configuration: the live state (which ifconfig en0 down changes) and the "configuration database" which corresponds to the settings created in the Network pane of System Preferences and/or the networksetup command.

In this particular case the -setwebproxy and -setsecurewebproxy options change the proxy settings for a particular network service - e.g. HT user3439894 - these set the proxy on the Wi-Fi network service.

networksetup -setwebproxy "Wi-Fi" localhost 8080
networksetup -setsecurewebproxy "Wi-Fi" localhost 8080

Depending on the actual network configuration will need to choose the appropriate service..

-setwebproxy networkservice domain portnumber authenticated username password

Set Web proxy for networkservice with domain and port number. Turns proxy on. Optionally, specify on or off for authenticated to enable and disable authenticated proxy support. Specify username and password if you turn authenticated proxy support on.

AND to turn off then look for

-setwebproxystate networkservice on | off

You can also use locations to quickly switch between network configurations - these are much easier to setup in the GUI. System Preferences -> Network (Edit Locations on the Locations dropdown). However, once setup, network setup has an easy way of switching (assuming you had a location named viaProxy or _to revert standard -

networksetup -switchtolocation viaProxy
networksetup -switchtolocation standard