Skip to content

Instantly share code, notes, and snippets.

@drunkpig
Created October 4, 2020 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drunkpig/4f3a6cf60408aa56268663aa66c4f911 to your computer and use it in GitHub Desktop.
Save drunkpig/4f3a6cf60408aa56268663aa66c4f911 to your computer and use it in GitHub Desktop.
macos setup proxy
class MacSetting(object):
def __init__(self, args):
self.device = None
self.listen = None
self.modes = None
self.mode_name = None
for option in args.listen:
protos = [x.name for x in option.protos]
if option.unix or 'ssl' in protos or 'secure' in protos:
continue
if 'socks5' in protos:
self.modes = ['setsocksfirewallproxy']
self.mode_name = 'socks5'
self.listen = option
break
if 'http' in protos:
self.modes = ['setwebproxy', 'setsecurewebproxy']
self.mode_name = 'http'
self.listen = option
break
if self.listen is None:
print('No server listen on localhost by http/socks5')
ret = subprocess.check_output(['/usr/sbin/networksetup', '-listnetworkserviceorder']).decode()
en0 = next(filter(lambda x: 'Device: en0' in x, ret.split('\n\n')), None)
if en0 is None:
print('Cannot find en0 device name!\n\nInfo:\n\n'+ret)
return
line = next(filter(lambda x: x.startswith('('), en0.split('\n')), None)
if line is None:
print('Cannot find en0 device name!\n\nInfo:\n\n'+ret)
return
self.device = line[3:].strip()
for mode in self.modes:
subprocess.check_call(['/usr/sbin/networksetup', mode, self.device, 'localhost', str(self.listen.port), 'off'])
print(f'System proxy setting -> {self.mode_name} localhost:{self.listen.port}')
def clear(self):
if self.device is None:
return
for mode in self.modes:
subprocess.check_call(['/usr/sbin/networksetup', mode+'state', self.device, 'off'])
print('System proxy setting -> off')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment