How to set proxy settings on MacOS using python

2019-02-27 10:49发布

How to change the internet proxy settings using python in MacOS to set Proxy server and Proxy port

I do that with windows using this code:

import _winreg as winreg

INTERNET_SETTINGS = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings', 0, winreg.KEY_ALL_ACCESS)

def set_key(name, value):
    _, reg_type = winreg.QueryValueEx(INTERNET_SETTINGS, name)
    winreg.SetValueEx(INTERNET_SETTINGS, name, 0, reg_type, value)

set_key('ProxyEnable', 0)
set_key('ProxyOverride', u'*.local;<local>')  # Bypass the proxy for localhost
set_key('ProxyServer', u'proxy.example.com:8080')

is this possible to do it on MacOS ?

1条回答
做个烂人
2楼-- · 2019-02-27 11:29

After a long time fo search, i found this way of how to change proxy on MacOs using python.

We need to use networksetup via terminal.

To set http proxy server on MacOS using python:

import os

proxy = "proxy.example.com"
port = 8080

def Proxy_on():
    os.system('networksetup -setwebproxy Ethernet '+proxy+' '+port)

Proxy_on()

and to turn it off:

import os

proxy = "proxy.example.com"
port = 8080

def Proxy_off():
    os.system('networksetup -setwebproxystate Ethernet off')

Proxy_off()

If the network service isn't named just "Ethernet", you may need to parse networksetup -listallnetworkservices or -listnetworkserviceorder to get the correct name.

查看更多
登录 后发表回答