SSID = "change me"
password = "change me"

import ctypes
from subprocess import PIPE, Popen
import re
import os

def ecmd(command):
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    return out,err

print(ecmd('netsh wlan disconnect'))
out,err = ecmd('netsh wlan export profile folder="C:\ProgramData\" name="%s" key=clear'%(SSID))
if out:
    filename = "Wi-Fi-%s.xml"%(SSID)
    filepath = "C:\ProgramData\%s"%(filename)
    with open(filepath, 'r') as f:
        xml_content = f.read()
    new_xml_content = re.sub('<keyMaterial>.*</keyMaterial>','<keyMaterial>%s</keyMaterial>'%(password),xml_content)
    with open(filepath, 'w') as f:
        f.write(new_xml_content)
    out,err = ecmd('netsh wlan delete profile name="%s"'%(SSID))
    if out:
        out,err = ecmd('netsh wlan add profile filename="%s"'%(filepath))
        if out:
            print(out)
            print("successfully changed the wifi password")
            os.remove(filepath)
        else:
            print(err)
            print("couldn't add the wifi profile")
    else:
        print(err)
        print("couldn't delete the wifi profile")
else:
    print(err)
    print("couldn't export the wifi profile")
        
