import _winreg
import os
import ctypes
import re
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)

def ecmd(command):   
    from subprocess import Popen, PIPE
    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
        out, err = obj.communicate()
        return out,err

with disable_file_system_redirection():
    users=os.popen("net users").read().split()[5:-4]
    fil_users=[i.strip() for i in users if i.strip()!="Administrator" and i.strip()!="DefaultAccount" and i.strip()!="Guest" and i.strip()!="WDAGUtilityAccount"]
    userout = os.popen('query user').read()
    curusername = re.findall("(.*)Active",userout)[0].split()[0]
    adminuser = os.popen("net localgroup administrators").read().splitlines()[7:-2]
    for i in adminuser:
        if i.strip() in fil_users:
            fil_users.remove(i.strip())
        else:
            pass
    curcheck = list(filter(lambda x: x.lower()==curusername.lower(),fil_users))
    if curcheck:
        try:
            sid = os.popen("wmic useraccount where name=\"%s\" get sid"%(curusername)).read().splitlines()[1].strip()
            key = _winreg.CreateKeyEx(_winreg.HKEY_USERS,"%s\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"%(sid),0,_winreg.KEY_ALL_ACCESS)
            _winreg.SetValueEx(key, "NoControlPanel", 0, _winreg.REG_DWORD, 1)
            _winreg.CloseKey(key)
        except Exception as err:
            print(err)
        else:
            fil_users.remove(curcheck[0])
            print("successfully limited the system access for the normal user - %s"%(curusername))
    for i in fil_users:
        if os.path.exists("C:\\Users\\%s\\ntuser.dat"%(i)):
            out,err = ecmd("reg load HKU\\%s C:\\Users\\%s\\ntuser.dat"%(i,i))
            if out:
                try:
                    key = _winreg.CreateKeyEx(_winreg.HKEY_USERS,"%s\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"%(i),0,_winreg.KEY_ALL_ACCESS)
                    _winreg.SetValueEx(key, "NoControlPanel", 0, _winreg.REG_DWORD, 1)
                    _winreg.CloseKey(key)
                except Exception as err:
                    print(err)
                else:
                    unLoad = os.popen("reg unload HKU\\%s"%(i)).read()
                    print("successfully limited the system access for the normal user - %s"%(i))
            else:
                print(err)