sysproxy.py
'''Sets Windows' proxy configurations easily.
This script allows user to update Windows proxy settings easily,
by using predefined values assigned to proxies identified by
keywords.
Note that it'll also refresh your system to guarantee that all
settings take effect. Although in the tests it seemed unnecessary
(Windows 8.1), it's considered just a guarantee.
Of course, you must reload all pages after running this script, but
the first thing you gotta do before running it is to setup the PROXIES
variable, creating an ID for each proxy in your environment, so you
can refer to it by using that ID as a parameter.
The "default" and "off" words are reserved, one for your proxy default
settings and the other to disable proxy --remember to set up the
"default" keyword properly. Running this script without parameters
will print the current proxy settings on screen.
Usage examples:
$ python winproxy.py
$ python winproxy.py off
$ python winproxy.py proxyid
Based on: https://bitbucket.org/canassa/switch-proxy
'''
__author__ = 'José Lopes de Oliveira Júnior'
__license__ = 'MIT'
import ctypes
from sys import argv
from sys import exit
from winreg import OpenKey, QueryValueEx, SetValueEx
from winreg import HKEY_CURRENT_USER, KEY_ALL_ACCESS
PROXIES = {
'default': {
'enable': 1,
'override': u'127.0.0.1;localhost;<local>',
'server': u'10.0.0.5:8080'
},
'off': {
'enable': 0,
'override': u'-',
'server': u'-'
},
'proxyid': {
'enable': 1,
'override': u'127.0.0.1;localhost;<local>',
'server': u'10.0.1.5:8080'
},
'my_proxy':{
'enable': 1,
'override': u'localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>',
'server': u'10.0.0.2:9091'
}
}
INTERNET_SETTINGS = OpenKey(HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
0, KEY_ALL_ACCESS)
def set_key(name, value):
SetValueEx(INTERNET_SETTINGS, name, 0,
QueryValueEx(INTERNET_SETTINGS, name)[1], value)
if __name__ == '__main__':
try:
proxy = argv[1]
except IndexError:
print(f'Enable....: {QueryValueEx(INTERNET_SETTINGS,"ProxyEnable")[0]}')
print(f'Server....: {QueryValueEx(INTERNET_SETTINGS,"ProxyServer")[0]}')
print(f'Exceptions: {QueryValueEx(INTERNET_SETTINGS,"ProxyOverride")[0]}')
exit(0)
try:
set_key('ProxyEnable', PROXIES[proxy]['enable'])
set_key('ProxyOverride', PROXIES[proxy]['override'])
set_key('ProxyServer', PROXIES[proxy]['server'])
# granting the system refresh for settings take effect
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
internet_set_option(0, 37, 0, 0) # refresh
internet_set_option(0, 39, 0, 0) # settings changed
except KeyError:
print(f'Registered proxies: {PROXIES.keys()}')
exit(1)
exit(0)
代码借鉴自:https://gist.github.com/lopes/9bf99ff7cf3d6e8d4c98972bb3262985
相关文章:python设置win系统代理 - 知乎