I often need to change the network proxies settings frequently due to the need to bypass the GFW when accessing websites that are considered “bad”, and have to set the settings back to not using any proxies when accessing “good” websites.
Doing so in Firefox is easy thanks to the little yet handy plugin called SwitchProxy, but for Safari or other applications which use the global system settings of Mac OS, one has to go through many steps in System Preferences to set them, and then go through the exact steps again to unset them. Too repetitive. I wish there is a way to set and unset proxies easily, but I cannot find one. I bit the bullet and use AppleScript (yuck) to do that, here’s the complete script (beware, this is my first AppleScript program):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
set proxyServer to "localhost" set proxyPort to "30000" tell application "System Preferences" activate set the current pane to pane id "com.apple.preference.network" get the name of every anchor of pane id "com.apple.preference.network" reveal anchor "Proxies" of pane id "com.apple.preference.network" end tell tell application "System Events" tell process "System Preferences" tell window "Network" tell sheet 1 tell tab group 1 tell group 1 repeat with n from 1 to 3 tell scroll area 1 tell table 1 select row n tell row n click checkbox 1 set turnOnProxy to value of checkbox 1 end tell end tell end tell if turnOnProxy is 1 then tell group 1 set focused of text field 1 to true set value of text field 1 to proxyPort set focused of text field 2 to true set value of text field 2 to proxyServer end tell end if end repeat end tell end tell click button "OK" end tell click button "Apply" end tell end tell end tell ignoring application responses tell application "System Preferences" to quit end ignoring if turnOnProxy is 1 then say "Proxies are set" else say "Proxies are unset" end if |
I hate to use AppleScript as it simply plays back what a human does, and so the speed is slow, which takes about 5 seconds to finish. I tried to do that by shell script but I couldn’t find the right way to do so, having looked at the defaults
command but seems it is not capable at what I want. Anybody knows?