Search code examples
pythonwindowsregistrywinreg

Editing a REG_BINARY using _winreg


I'm trying to make a simple program that can enable or disable the proxy settings in windows using _winreg. There are 2 settings in the registry that I'll need to change to do this. The first is ProxyEnable which is a REG_DWORD, the second is DefaultConnectionSettings which is a REG_BINARY. I can access both keys, and making the change to the dword was no problem. Where I am having a problem is with the second key, I can open and query it, but I'm not sure how to change it. It's a string so I thought I could perhaps slice it and just add the bit that I want, but the original value is '\x03' and I need to change it to '\x09' which when entered into python becomes '\t' since I guess it is the escaped 'horizontal tab'. I'm pretty new to Python so I realise I may be doing this completely the wrong way, any advice would be appreciated.

key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections",0, wreg.KEY_ALL_ACCESS)

This is the key I need help with, I can open and read it but I have no idea how to correctly work with it. I basically just need the 9th byte to change from 03 to 09 and then back to 03 when I want to re-enable the proxy.


Solution

  • Since you have the registry key open the next thing you need to is get the DefaultConnectionSettings registry value:

    (value, regtype) = wreg.QueryValueEx(key, "DefaultConnectionSettings")
    

    You now need to change a single byte in the value. Unfortunately the value will be represented as a Python string, and in Python strings are immutable. So you need to create a new string with that one byte changed:

    if regtype == wreg.REG_BINARY:
        value = value[:8] + chr(0x09) + value[9:]
    

    Finally write the new value back into the registry:

        wreg.SetValueEx(key, "DefaultConnectionSettings", None, regtype, value)