python 切换代理

from ctypes import windll
import winreg
from os import path, getcwd

from win10toast import ToastNotifier

from configparser import ConfigParser, NoOptionError, NoSectionError

config_path = path.join(getcwd(), 'config')
config_file = path.join(config_path, 'config.ini')


class ChangeProxy:

    def __init__(self) -> None:
        self.INTERNET_OPTION_REFRESH = 37
        self.INTERNET_OPTION_SETTINGS_CHANGED = 39
        self.REG_PATH = 'Software\Microsoft\Windows\CurrentVersion\Internet Settings'
        self.SECTION = 'change proxy'
        self._parser_config()


    def _parser_config(self):
        conf = ConfigParser()
        conf.read(config_file, encoding='utf-8')
        self.items = conf.items(self.SECTION)
        is_null_include = 0
        proxy_ip = []
        ignore_ip = []
        self.proxy_ignore = []
        for key, value in self.items:
            if key.startswith('proxy_ip'):
                proxy_ip.append(value)
            if key.startswith('ignore_ip'):
                ignore_ip.append(value)
        for i in range(len(proxy_ip)):
            if proxy_ip[i] == '' and ignore_ip[i] == '':
                self.proxy_ignore.append([0, proxy_ip[i], ignore_ip[i]])
                is_null_include = 1
            else:
                self.proxy_ignore.append([1, proxy_ip[i], ignore_ip[i]])
        if is_null_include == 0:
            self.proxy_ignore.append([0, '', ''])
            conf.set(self.SECTION, f'proxy_ip{len(self.proxy_ignore)}', '')
            conf.set(self.SECTION, f'ignore_ip{len(self.proxy_ignore)}', '')
            with open(config_file, 'w') as f:
                conf.write(f)


    def _set_proxy(self, mod, proxyIp, IgnoreIp):
        # function  :   设置代理的注册表文件
        # structure :   none
        # usage     :   change_proxy = ChangeProxy()
        #               change_proxy._set_proxy(1, ORIGINAL_PROXY_IP, ORIGINAL_IGNORE_IP)
        # parameter :   mod      : 是否启动,1为启动0为关闭
        #               proxyIp  : 代理IP
        #               IgnoreIp : 忽略IP
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.REG_PATH, 0, winreg.KEY_WRITE)
            winreg.SetValueEx(key, 'ProxyEnable', 0, winreg.REG_DWORD, mod)
            winreg.SetValueEx(key, 'ProxyServer', 0, winreg.REG_SZ, proxyIp)
            winreg.SetValueEx(key, 'ProxyOverride', 0, winreg.REG_SZ, IgnoreIp)
        except Exception as e:
            print('ERROR: ' + str(e.args))
        finally:
            None

        internet_set_option = windll.Wininet.InternetSetOptionW
        internet_set_option(0, self.INTERNET_OPTION_REFRESH, 0, 0)
        internet_set_option(0, self.INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)


    @staticmethod
    def _get_proxy(reg_path):
        # function  :   获取代理的注册表值
        # structure :   list [int, str]
        # usage     :   change_proxy = ChangeProxy()
        #               change_proxy._get_proxy(reg_path)
        # parameter :   reg_path : 注册表地址
        proxy_status = ''
        proxy_ip = ''

        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path, 0, winreg.KEY_READ)
            proxy_status, _type = winreg.QueryValueEx(key, 'ProxyEnable')
            proxy_ip, _type = winreg.QueryValueEx(key, 'ProxyServer')
        except Exception as e:
            print('ERROR: ' + str(e.args))
        finally:
            None

        return str(proxy_status), str(proxy_ip)

    def change_proxy(self):
        # function  :   修改代理的注册表值
        # structure :   none
        # usage     :   change_proxy = ChangeProxy()
        #               change_proxy.change_proxy()
        # 原代理
        ip, status = self._get_proxy(self.REG_PATH)
        print(f'原代理为: {ip}, 状态为: {status}')
        # 修改
        self.proxy_ignore.append(self.proxy_ignore.pop(0))
        s, p, i = self.proxy_ignore[0]
        self._set_proxy(s, p, i)
        for i in range(len(self.proxy_ignore)):
            conf = ConfigParser()
            conf.read(config_file, encoding='utf-8')
            conf.set(self.SECTION, f'proxy_ip{i + 1}', self.proxy_ignore[i][1])
            conf.set(self.SECTION, f'ignore_ip{i + 1}', self.proxy_ignore[i][2])
            with open(config_file, 'w', encoding='utf-8') as f:
                conf.write(f)
        # 当前代理
        ip, status = self._get_proxy(self.REG_PATH)
        print(f'当前代理为: {ip}, 状态为: {status}')


    def disableProxy(self):
        # function  :   清空代理的注册表值
        # structure :   none
        # usage     :   change_proxy = ChangeProxy()
        #               change_proxy.disableProxy()
        print(' Empty proxy')
        self._set_proxy(0, '', '')
        print(' Empty success')


if __name__ == "__main__":
    change_proxy = ChangeProxy()
    change_proxy.change_proxy()

你可能感兴趣的:(python,windows,linux)