[python]Disabling and enabling Windows proxy settings

References:
https://superuser.com/questions/1113796/how-to-run-a-python-script-with-cmd-exe-and-make-it-invisible/1113801
https://stackoverflow.com/questions/31348111/setting-proxy-settings-in-windows-with-python-using-internetsetoption

Requirements

  • Disable and enable the proxy without closing internet explorer.
  • Enable the proxy setting when auto configuration url (PAC location) is not available.
  • Trigger the script to disable proxy when your laptop is connected out of office.
  • Trigger the script to enable the proxy when your laptop is connected to your domain in office.
  • Convert the python scripts to executable because endusers’ computers do not have python installed.

Python as an option for the proxy toggling script
Here is the entire python script that does the job of enabling. You can actually disabling and enabling the proxy setting in registry with regedit, the path is hkcu\software\Microsoft\Windows\CurrentVersion\Internet Settings, which can be accomplished in command line: https://stackoverflow.com/questions/18439373/batch-file-to-disable-internet-options-proxy-server, but this method requires you to close the Internet explorer and open again for the registry change to take effect.

Another constraint is that your environment cannot use powershell script to do the proxy toggling because powershell policy is under constrained mode, but you are familiar with python.

Python script that does the enable proxy
Your vpn client asserts its own proxy pac file location onto internet option, in the script it checks if AutoConfigURL is available or not in the registry. If it is not available the proxy setting will be enabled, if it is available the proxy setting stays disabled.

import winreg
import ctypes
import os
from pexpect import popen_spawn
# pexpect.run and pexpect.spawn is not available in Windows, these methods are only for unix like OS.
# popen_spawn is available for Windows, See documentation:
# https://pexpect.readthedocs.io/en/stable/overview.html#pexpect-on-windows

cmd = "C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\VPNcli.exe"
state_connected = ">> state: Connected"
#state_disconnected = ">> state: Disconnected"


# Cisco anyconnect vpncli.exe status
def check_vpn_status(cmd):
    child = popen_spawn.PopenSpawn(cmd)
    child.expect("VPN> ")
    child.sendline("state")
    child.expect("VPN> ")
    result = child.before.decode("utf-8").strip()
    child.expect("VPN> ")
    child.sendline("exit")
    return result


# This is to set the DWORD of the registry
def set_key(name, value):
    _, reg_type = winreg.QueryValueEx(INTERNET_SETTINGS, name)
    winreg.SetValueEx(INTERNET_SETTINGS, name, 0, reg_type, value)


with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                    r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
                    0, winreg.KEY_ALL_ACCESS) as INTERNET_SETTINGS:
    if os.path.exists(cmd):
        status = check_vpn_status(cmd)

        if state_connected in status:
            try:
                winreg.QueryValueEx(INTERNET_SETTINGS, 'AutoConfigURL')
                set_key('ProxyEnable', 0)
            except:
                set_key('ProxyEnable', 1)
        else:
            set_key('ProxyEnable', 1)
    else:
        set_key('ProxyEnable', 1)

# Refresh and update status changed in registry.
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)

The ctypes module is required to refresh the setting so that Internet Explorer does not need to be closed after registry is changed.

Disable proxy
This script only cares about disabling hence there is no need to check other things.

import winreg
import ctypes


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)

INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)

Task scheduler triggers
This event will trigger if laptop is connected to public network.

&ltQueryList&gt&ltQuery Id="0" Path="Microsoft-Windows-NetworkProfile/Operational"&gt&ltSelect Path="Microsoft-Windows-NetworkProfile/Operational"&gt *[System[(EventID=10000)]] and *[EventData[Data[@Name="Category"] and (Data='0')]] &lt/Select&gt&lt/Query&gt&lt/QueryList&gt

This event will trigger if laptop is connected to domain network.

&ltQueryList&gt&ltQuery Id="0" Path="Microsoft-Windows-NetworkProfile/Operational"&gt&ltSelect Path="Microsoft-Windows-NetworkProfile/Operational"&gt *[System[(EventID=10000)]] and *[EventData[Data[@Name="Category"] and (Data='2')]] &lt/Select&gt&lt/Query&gt&lt/QueryList&gt

Visual basic to suppress the black command console from appearing
The visual basic is set to run the script compile in exe by pyinstaller, run pyinstaller --onefile yourscript.py, the reason is because cmd cannot suppress the black command prompt console but actually creates it, hence i need to use wscript to run the vbs in order to run the script “silently”.

Set WinScriptHost = CreateObject("Wscript.shell")
WinScriptHost.Run Chr(34) & "C:\temp\disable_proxy.exe" & Chr(34), 0
Set WinScriptHost = Nothing

Just change the path C:\temp\disable_proxy.exe according to your script path.

Advertisements
This entry was posted in Python, Scripting, Windows and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s