change proxy on mac osx programmatically

一个人想着一个人 提交于 2019-12-04 14:21:08
Dmitry Isaev

From this answer, here is a sample script:

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

if [ -n "$e" ]; then
  echo "Turning on proxy"
  networksetup -setsocksfirewallproxystate wi-fi on
else
  echo "Turning off proxy"
  networksetup -setsocksfirewallproxystate wi-fi off
fi

It swiches (on/off) the SOCKS proxy for the user's Wi-Fi connection.

You can use this idea to make the script for your needs. You can implement your desired logic in a bash script like that or in Cocoa.

  • Use networksetup -listallnetworkservices to list all connections.
  • Use networksetup -setwebproxy to setup proxy for a particular connection.

For example, here's my Terminal output:

$ networksetup -listallnetworkservices
An asterisk (*) denotes that a network service is disabled.
MBBEthernet
Wi-Fi
Wi-Fi Modem Yota 4G LTE
Bluetooth PAN
Thunderbolt Bridge
iPhone

$ networksetup -setwebproxy some bad args
** Error: The parameters were not valid.

$ networksetup -setwebproxy Wi-Fi 1.2.3.4 8080

The last command gave the empty stdout, it means success.

See also man networksetup.

How to execute a shell command from a Cocoa app.

The above commands executed from Terminal app asked for authorization. I'm sorry I'm not sure if you can leave it "as is" (just launch your NSTask, OS X will do the rest), or you need to obtain proper credentials via SFAuthorization before doing that.

CFDictionaryCreateMutableCopy would do the trick, but even after you successfully changed the dictionary, SCDynamicStoreSetMultiple just has no effect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!