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
import re
import ctypes
import time
from subprocess import PIPE, Popen
import sys
import difflib
import socket
import ssl 
from email.mime.multipart import MIMEMultipart
from email.message import Message
from email.mime.text import MIMEText
import smtplib
import mimetypes

cmd_on='wevtutil qe Security "/q:*[System [(EventID=4624)]]" /rd:true /f:text /c:1'
Date=[]
Time=[]
Acc_name=[]
Date1=[]
Time1=[]
Acc_name1=[]
flag=0

try:
    workdir=os.environ['PROGRAMDATA']+r'\temp'
    if not os.path.exists(workdir):
        os.mkdir(workdir)      
except:
    workdir=os.environ['SYSTEMDRIVE']

New_ON=workdir+r"\New_LogOn.txt"
Old_ON=workdir+r"\Old_LogOn.txt"
File_To_Send=workdir+r"\Report.txt"

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 alert(arg): 
   sys.stderr.write("%d%d%d" % (arg, arg, arg))

Device=str(os.environ['COMPUTERNAME'])
ip = socket.gethostbyname(socket.gethostname())

def gmail(sender_email,password,receiver,text):
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver
    msg["Subject"] = "Admin Login Details for the device %s. account name is %s and IP is %s"%(Device,kp,ip)
    textfile = "Please find the last Logging details of the local Admin user below.\n\n" + text
    attachment = MIMEText(textfile, _subtype="plain")
    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")
   
def command(CMD):        
    from subprocess import PIPE, Popen
    with disable_file_system_redirection():
        OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
        out, err = OBJ.communicate()
        if err:
            print(err)
        else:
            return out
    
with disable_file_system_redirection():
    userout = command('query user')
    username = re.findall(r"(.*)\s+\S+\s+\S+\s+Active",userout)[0].strip()
    admin_query = os.popen(r'wmic /Node:"%ComputerName%" path win32_groupuser where (groupcomponent="win32_group.name=\"administrators\",domain=\"%ComputerName%\"")').read()
    admin_names = re.findall('Name="(.*)"',admin_query)


def logon(file0):
    out=command(cmd_on)
    if out:
        user = username
        Acc_name.append("Account Name : "+user)
        gt=re.findall('Date:(.*)', out)
        date=re.findall('(.*)T', gt[0])
        Date.append("Log_On Date : "+date[0].strip())
        time=re.findall('T(.*)', gt[0])
        Time.append("Log_On Time : "+time[0].strip())
        with open(file0, 'w+') as fr:
            fr.write(str(Acc_name[0])+"\n")
            fr.write(str(Date[0])+"\n")
            fr.write(str(Time[0])+"\n")
    else:
        print("\nFailed to retrieve LOG_ON details\n")


def prnt():
    with open(File_To_Send, 'a+') as dr:
        with open(New_ON, 'r') as de:
            for i in de:
                dr.write(i)
        dr.write("\n")
        
def to_alert(Old_ON, New_ON):
    flag=0
    with open(Old_ON) as file:
        data=file.read()
        with open(New_ON) as file:
                data2=file.read()
                text1Lines = data.splitlines(1)
                text2Lines = data2.splitlines(1)
                diffInstance = difflib.Differ()
                diffList = list(diffInstance.compare(text1Lines,text2Lines ))
                for line in diffList:
                        if line[0] == '+':
                                flag=1

    return flag
           
def file_change():
    open(workdir+r"\count.txt", 'a').close()
    os.rename(workdir+r"\New_LogOn.txt",workdir+r"\Old_LogOn.txt" )
    os.remove(File_To_Send)
    

def rem_change():
    os.remove(workdir+r"\Old_LogOn.txt")
    os.rename(workdir+r"\New_LogOn.txt",workdir+r"\Old_LogOn.txt" )
    if os.path.isfile(File_To_Send):
        os.remove(File_To_Send)

def txt_send():
    with open(File_To_Send, 'r') as rr:
            contents =rr.read()
            c1=re.findall("Account Name :(.*)",contents)
            c2=set(c1)
            c3=list(c2)
            kk=', '.join(c3)
            return kk,contents

if os.path.isfile(workdir+r"\count.txt"):
    logon(New_ON)
    val=to_alert(Old_ON, New_ON)

    if val>0:
        prnt()
        kp,cont1=txt_send()
        if 'SYSTEM' and 'user' in kp:
            print(cont1.strip())
            alert(0)
        else:
            for ad in admin_names:
                if ad in kp:
                    print("New Admin User has logged in within the time interval.Please find the details below.")
                    print(cont1.strip())
                    gmail(Sender,Password,Receiver,cont1)
                    alert(1)
                    break
    else:
        alert(0)
        print("\nNo User has logged in within the time interval.\n")
    rem_change()
else:
    print("Running this procedure for the first time in this Endpoint.")
    logon(New_ON)
    prnt()
    kp,cont1=txt_send()
    
    if os.path.isfile(File_To_Send):
        for ad in admin_names:
            if ad in kp:
                print("New Admin User has logged in within the time interval.Please find the details below.")
                print(cont1.strip())
                gmail(Sender,Password,Receiver,cont1)
                break
    else:
        print("Failed to generate report file\n")
    file_change()
    alert(1)