import os
from subprocess import PIPE, Popen
import ctypes

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)

class ExecutionPolicy:
    def __enter__(self):
        with disable_file_system_redirection():
            #getting current executionpolicy
            self.old_policy = os.popen('powershell "Get-ExecutionPolicy"').read().strip()
            #setting execution policy to RemoteSigned
            os.popen('powershell "Set-ExecutionPolicy RemoteSigned"').read()
    def __exit__(self, type, value, traceback):
        with disable_file_system_redirection():
            #setting execution policy back to previous policy
            os.popen('powershell "Set-ExecutionPolicy %s"'%(self.old_policy)).read()
            
def ecmd(command):
    from subprocess import Popen, PIPE
    import ctypes
    
    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    return ret,out,err
     
PScontent = r"""
function Get-LocalAdministrators {  
    param ($strcomputer)  

    $admins = Get-WmiObject win32_groupuser -computer $strcomputer   
    $admins = $admins |? {$_.groupcomponent -like '*"Administrators"'}  

    $admins | ForEach-Object {  
    $_.partcomponent -match ".+Domain\=(.+)\,Name\=(.+)$" > $nul  
    $matches[1].trim('"') + "\" + $matches[2].trim('"')  
    }  
}

Get-LocalAdministrators localhost
"""

ps_name='powershell_file.ps1'
ps_path=os.path.join(os.environ['TEMP'], ps_name)
with open(ps_path, 'wb') as wr:
    wr.write(PScontent)
    
with ExecutionPolicy():      
    ret,out,err = ecmd('powershell "%s"'%ps_path)

if ret==0:
    if out:
        with disable_file_system_redirection():			
            DomainName=os.popen('systeminfo | findstr /B /C:"Domain"').read().split()[-1].split('.')[0]
        LG_admins = [x.strip() for x in out.strip().splitlines() if DomainName.lower() in x.lower()]
        if LG_admins:
            for i in LG_admins:
                print(ecmd('net localgroup administrators "%s" /delete'%(i)))
                print('domain user - "%s" has been successfully removed'%(i))
        else:
            print("No Domain user is found in localgroup administrators")
    else:
        print("couldn't get any information about localgroup administrators")
else:
    print(ret)
    print(err)