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 getpass
import time
import subprocess
from subprocess import PIPE, Popen
import sys
import difflib
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

cmd_off='wevtutil qe Security "/q:*[System [(EventID=4634)]]" /rd:true /f:text /c:1'
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

Device=str(os.environ['COMPUTERNAME'])
ip = socket.gethostbyname(socket.gethostname())
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"
New_Off=workdir+r"\New_LogOff.txt"
Old_ON=workdir+r"\Old_LogOn.txt"
Old_Off=workdir+r"\Old_LogOff.txt"
File_To_Send=workdir+r"\Report.txt"

def gmail(sender_email,password,receiver,text):
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver
    msg["Subject"] = "Logging Details for the device %s. account name is  %s and IP is %s"%(Device,kp,ip)
    textfile = "Please find the last Logging details of 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 alert(arg): 
   sys.stderr.write("%d%d%d" % (arg, arg, arg))

   
def command(CMD):        
    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)
    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
    
userout = command('query user')
username = re.findall("(.*)Active",userout)[0].split()[0]

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 logoff(file1):
    out=command(cmd_off)
    if out:
        gl=re.findall('Account Name:(.*)', out)
        Acc_name1.append("Account Name : "+gl[0].strip())
        gt=re.findall('Date:(.*)', out)
        date=re.findall('(.*)T', gt[0])
        Date1.append("Log_Off Date : "+date[0].strip())
        time=re.findall('T(.*)', gt[0])
        Time1.append("Log_Off Time : "+time[0].strip())
        with open(file1, 'w+') as fr:
            fr.write(str(Acc_name1[0])+"\n")
            fr.write(str(Date1[0])+"\n")
            fr.write(str(Time1[0])+"\n")

    else:
        print "\nFailed to retrieve LOG_OFF 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")
    print "\n"

    with open(File_To_Send, 'a+') as dr:
        with open(New_Off, 'r') as de:
            for i in de:
                dr.write(i)
        
def to_alert(Old_ON, Old_Off, New_ON, New_Off):
    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

    with open(Old_Off) as file:
        data=file.read()
        with open(New_Off) 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.rename(workdir+r"\New_LogOff.txt",workdir+r"\Old_LogOff.txt" )
    os.remove(File_To_Send)
    

def rem_change():
    os.remove(workdir+r"\Old_LogOn.txt")
    os.remove(workdir+r"\Old_LogOff.txt")
    os.rename(workdir+r"\New_LogOn.txt",workdir+r"\Old_LogOn.txt" )
    os.rename(workdir+r"\New_LogOff.txt",workdir+r"\Old_LogOff.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)
    logoff(New_Off)
    val=to_alert(Old_ON, Old_Off, New_ON, New_Off)

    if val>0:
        print "\nNew User has logged in or Logged off within the time interval.Please check mail for details.\n"
        prnt()
        kp,cont1=txt_send()
        gmail(Sender,Password,Receiver,cont1)
        alert(1)
    else:
        alert(0)
        print "\nNo User has logged in or Logged off within the time interval.\n"
    rem_change()
else:
    print "Running this procedure for the first time in this Endpoint."
    logon(New_ON)
    logoff(New_Off)
    prnt()
    kp,cont1=txt_send()
    
    if os.path.isfile(File_To_Send):
        gmail(Sender,Password,Receiver,cont1)
    else:
        print "Failed to generate report file to send to mail\n"
    file_change()
    alert(1)