0

see code.I want to open the proxy and then close the proxy. in fact, i find it is normal to turn on proxy and turn off proxy, but they cannot be used at the same time. I haven't found a solution yet. Please help me. Thank you

import ctypes
import winreg
import time
import requests

xpath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings"
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
def setProxy(enable, proxy):
    try:
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, xpath, 0, winreg.KEY_WRITE)
        winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, enable)
        winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ, proxy)
        # 关闭自动配置脚本
        winreg.SetValueEx(key, "AutoConfigURL", 0, winreg.REG_SZ, "")
        # 设置刷新
        INTERNET_OPTION_REFRESH = 37
        INTERNET_OPTION_SETTINGS_CHANGED = 39
        internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
        internet_set_option(0,INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
    except Exception as e:
        print("ERROR: " + str(e))
    finally:
        None


def enableProxy(proxy):
    print(" Setting proxy")
    setProxy(1, proxy)
    print(" Setting success")

#关闭清空代理
def disableProxy():
    print(" Empty proxy")
    setProxy(0, "")
    print(" Empty success")

if __name__ == '__main__':
    enableProxy('42.51.13.68:16819')
    print(requests.get("http://dev.kdlapi.com/testproxy").text)
    time.sleep(1)
    disableProxy()
    print(requests.get("http://dev.kdlapi.com/testproxy").text)
jasonyang
  • 83
  • 5

2 Answers2

1

After setting the IE options and registry, you have to press F5 key to refresh the IE browser or restart the IE browser. More detail information, you could check this link.

Edit:

Besides,we could also use the DefaultConnectionSettings registry key to set the IE browser proxy, please refer to the following steps and this thread:

  1. Open Registry Editor
  2. Navigate to "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
  3. Check the "DefaultConnectionSettings" key value, it logs the proxy setting.
Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • thanks. this refresh code can solve this problem, but I find that it is not feasible for me to set up IE proxytwice in a script. – jasonyang Apr 29 '20 at 15:26
  • As far as I know, there has another method to set the IE browser proxy, you could try to open Registry Editor, and navigate to `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections`, then check the `DefaultConnectionSettings` key value, it logs the proxy setting. Please check it. you could try to change the setting using this registry key, and check whether it could work well in a script. I checked it using the Command Prompt, after change the value, it seems that there is need to refresh the page but need to reopen the IE options. – Zhi Lv Apr 30 '20 at 11:32
  • Yes, I am using DefaultConnectionSettings to set the proxy, this [answer](https://stackoverflow.com/questions/1564627/how-to-set-automatic-configuration-script-for-a-dial-up-connection-programmati) solves this problem – jasonyang May 11 '20 at 10:38
  • @jasonyang, Congratulation! – Zhi Lv May 12 '20 at 05:50
0

The reason is that in terms of refresh, both setting agent and closing agent need to be refreshed before they can take effect, and they need to be refreshed after they are closed before they can take effect

import os
import sys
import time
import socks
import socket
import winreg
import kdl
import requests
from ctypes import windll

#### 设置代理 #####
SETTING_PATH = "Software\Microsoft\Windows\CurrentVersion\Internet Settings"
def _system_proxy(func):
    """系统代理装饰器"""

    def __wrapper(proxy_ip=u"", ignore_ip=u""):
        """
        系统代理设置
        :param proxy_ip: 代理ip
        :param ignore_ip: 忽略的ip
        :return: 开启状态,True开启,False关闭
        """
        internet_setting = winreg.OpenKey(winreg.HKEY_CURRENT_USER, SETTING_PATH, 0, winreg.KEY_ALL_ACCESS)
        internet_set_option = windll.Wininet.InternetSetOptionW

        def _set_key(name, value):
            """
            修改键值
            :param name: 系统键
            :param value: 键值
            """
            _, reg_type = winreg.QueryValueEx(internet_setting, name)
            winreg.SetValueEx(internet_setting, name, 0, reg_type, value)

        return func(_set_key, internet_set_option, proxy_ip, ignore_ip)

    return __wrapper


def system_proxy_status():
    """获取当前代理状态"""
    h_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, SETTING_PATH, 0, winreg.KEY_READ)
    ret_val = winreg.QueryValueEx(h_key, "ProxyEnable")
    try:
        ret_ser = winreg.QueryValueEx(h_key, "ProxyServer")
    except Exception as e:
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, SETTING_PATH, 0, winreg.KEY_WRITE)
        winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ, "")
        ret_ser = winreg.QueryValueEx(h_key, "ProxyServer")
    winreg.CloseKey(h_key)
    return ret_val[0], ret_ser[0]


@_system_proxy
def open_system_proxy(_set_key, internet_set_option, proxy_ip=u"", ignore_ip=u""):
    """开启系统代理"""
    _set_key('ProxyEnable', 1)  # 启用
    if ignore_ip:
        _set_key('ProxyOverride', ignore_ip)  # 忽略的地址
    if proxy_ip:
        _set_key('ProxyServer', proxy_ip)  # 代理IP及端口
    internet_set_option(0, 37, 0, 0)
    internet_set_option(0, 39, 0, 0)
    return False if system_proxy_status()[0] == 0 else system_proxy_status()[1] == proxy_ip


@_system_proxy
def close_system_proxy(_set_key, internet_set_option, proxy_ip="", ignore_ip=""):
    """关闭系统代理"""
    internet_set_option(0, 37, 0, 0)
    internet_set_option(0, 39, 0, 0)
    _set_key('ProxyEnable', 0)  # 停用
    return False if system_proxy_status()[0] == 0 else system_proxy_status()[1] == proxy_ip

However, it is not feasible to set it twice in a row.

def main():
    open_system_proxy(proxy_ip="114.231.105.223:22322")
    print(system_proxy_status())
    open_system_proxy(proxy_ip="101.22.195.128:22619")
    print(system_proxy_status())

if __name__ == '__main__':
    main()

The result shows that the IP set twice is the same, although I give different proxy.I'm still looking for a reason

(1, '')
(1, '114.231.105.223:22322')
(1, '114.231.105.223:22322')
jasonyang
  • 83
  • 5