Receiver = itsm.getParameter('EmailTo')  ## Provide an Toemail address where the mail need to be sent.
Sender = itsm.getParameter('EmailFrom')  ## Provide the From Email address from which the mail to be send
Password = itsm.getParameter('Password')               ##Provide password for from email
MailFlag = itsm.getParameter('MailFlag')  # Provide mail flag 1 or 0 (1 - outlook, 0 - gmail). the datatype should be a int.

import os
from subprocess import PIPE, Popen
import ctypes
import smtplib
import mimetypes
import socket
import ssl 
from email.mime.multipart import MIMEMultipart
from email.message import Message
from email.mime.text import MIMEText
import sys
import difflib,filecmp

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 alert(arg):
    sys.stderr.write("%d%d%d" % (arg, arg, arg))

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

devicename = os.environ['COMPUTERNAME']
ip = socket.gethostbyname(socket.gethostname())
text = ""

def gmail(sender_email,password,receiver,text):
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver
    msg["Subject"] = "local admin group membership change details for the DeviceName:%s and IP:%s"%(devicename,ip)
    attachment = MIMEText(text, _subtype="plain")
    attachment.add_header('Content-Disposition', 'attachment', filename="%s_localgroup_admin_changes.txt"%(devicename))
    msg.attach(attachment)
    if MailFlag:
        server = smtplib.SMTP("smtp.office365.com", 587)
    else:
        server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(sender_email,password)
    server.sendmail(sender_email, receiver, msg.as_string())
    server.quit()
    print("successfully sent the mail")

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='admin_list_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)

LG_admins = [x.strip() for x in out.strip().splitlines()]

file_dir= os.path.join(os.environ['ProgramData'],'AdminList')

if not os.path.exists(file_dir):
    os.makedirs(file_dir)
    print("running this script for the first time on this machine")

fileToSend1=os.path.join(file_dir,'adminlist1.txt')
fileToSend2=os.path.join(file_dir,'adminlist2.txt')

file1=fileToSend1
file2=fileToSend2

def files():
     if os.path.exists(fileToSend1):
         fnd=1
     else:
         fnd=2
     return fnd
    
def write():
    f=files()
    os.chdir(file_dir)
    if f==2:
        with open(fileToSend1, 'w+') as f:
            for i in LG_admins:
              f.write("%s\n"%(i))
                    
        with open(fileToSend2, 'w+') as f:
            for i in LG_admins:
              f.write("%s\n"%(i))
    if f==1:
        with open(fileToSend2, 'w+') as f:
            for i in LG_admins:
                f.write("%s\n"%(i))
          
  
def compare():
 global text
 ale=0
 with open(file1) as file:
  data=file.read()
 with open(file2) as file:
  data2=file.read()
 text1Lines = data.splitlines(1)
 text2Lines = data2.splitlines(1)  
 diffInstance = difflib.Differ()
 if len(text1Lines)==len(text2Lines):
     diffList = list(diffInstance.compare(text2Lines, text1Lines))
     li=[]
     li1=[]
     for line in diffList:
         if line.startswith('+'):
             k=line.strip().strip('+')
             li.append(k)
         if line.startswith('-'):
             k1=line.strip().strip('-')
             li1.append(k1)
     if li and li1:
         ale=1
         for i in li :
             for j in li1 :
                 print('old user "%s" from the localgroup administrators has been replaced with new user "%s"'%(i.strip(),j.strip()))
                 text+=('old user "%s" from the localgroup administrators has been replaced with new user "%s"\n'%(i.strip(),j.strip()))
     else:
         print("No changes in local administrators group")
         text += "No changes in local administrators group"
         ale=0
                  
 else:
     diffList = list(diffInstance.compare(text2Lines, text1Lines))
     for line in diffList:
      if line[0] == '-':
       print('new user "%s" has been added to localgroup administrators'%(line.strip('-').strip()))
       text +=('new user "%s" has been added to localgroup administrators\n'%(line.strip('-').strip()))
       ale=1
     diffList = list(diffInstance.compare(text1Lines, text2Lines))
     for line in diffList:
      if line[0] == '-':
       print('"%s" user has been removed from localgroup administrators'%(line.strip('-').strip()))
       text +=('"%s" user has been removed from localgroup administrators\n'%(line.strip('-').strip()))
       ale=1
 return ale

write()
        
def remove():
    os.remove(fileToSend1)
    os.rename(fileToSend2,fileToSend1)

c=compare()

if c==1:
    alert(1)
    gmail(Sender,Password,Receiver,text)
    remove()
    os.remove(ps_path)
else:
    alert(0)
    remove()
    os.remove(ps_path)