#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
check_days = 10
emailto=['xxxx@gmail.com']  ## Provide an Toemail address where the mail need to be sent.You can also provide any number of To eamil address For example: ['tamil@yopmail.com','sensor@yopmail.com']
emailfrom='xxxx@gmail.com' ## Provide the From Email address from which the mail to be send
password='xxxxx'               ##Provide password for from email
smtpserver='smtp.gmail.com'
port=587

msgbody=r'''Hi

The Device no check in for last %d days.

Thank you.'''%check_days

import os
import re
import ctypes
from subprocess import PIPE, Popen
import socket
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from datetime import datetime, date
import json
import sys

def alert(arg):
    sys.stderr.write("%d%d%d" % (arg, arg, arg))

def oscmd(command):
    obj = os.popen(command).read()
    return obj.strip()

def computername():
    return os.environ['COMPUTERNAME']

def ipaddress():
    return socket.gethostbyname(socket.gethostname())

subject='%s %s Alert : Device not Checkin!!!!!'%(computername(), ipaddress())

def emailreport(subject, emailto,emailfrom,password,smtpserver,port,msgbody):
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ",".join(emailto)
    msg["Subject"] = subject
    msg.preamble = subject
    body = MIMEText(msgbody)
    msg.attach(body)       
    try:
        server = smtplib.SMTP(smtpserver,port)
        server.ehlo()
        server.starttls()
        server.login(emailfrom, password)
        server.sendmail(emailfrom, emailto, msg.as_string())
        server.quit()
        return " \nThe email report has been sent to "+msg["To"]
    except Exception as e:
        return e

def ecmd(command):
    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)

    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    if ret==0:
        if out:
            return out.strip()
        else:
            return ret
    else:
        if err:
            return err.strip()
        else:
            return ret

gt=[]

try:
    wdir=os.environ['PROGRAMDATA']+'\\temp'
    if not os.path.exists(wdir):
        os.mkdir(wdir)
except:
    wdir=os.environ['SYSTEMDRIVE']

fp=wdir+'\\users.txt'
cmd="wmic useraccount get name"
obj=Popen(cmd, shell=True, stdout = PIPE, stderr = PIPE)
out, err = obj.communicate()

with open(fp, 'w+') as dr:
    dr.write(out)

with open(fp, 'r+') as dr:
    for i in dr: None if 'Name' in i or 'DefaultAccount' in i or 'Guest' in i or 'Administrator' in i or 'WDAGUtilityAccount' in i else gt.append(i.strip())
print gt
count_days = 0
for user in gt:
    comd = ecmd(r'net user %s | findstr /B /C:"Last logon"'%user)
    if comd != 1:
        if 'Last logon' in comd and 'Never' not in comd:
            comd = comd.split(' ')
            if comd[-1] in ('AM','PM'):
                login_date = comd[-3]
            else:
                login_date = comd[-2]
            currentMonth = datetime.now().month
            if '-' in login_date:
                date_split = login_date.split('-')
                currentMonth = '{:02d}'.format(currentMonth)
                month = ''
                date = ''
                year = ''
                date_format = ''
                if int(currentMonth) == int(date_split[0]) or int(currentMonth) == int(date_split[1]) or int(currentMonth) == int(date_split[2]):
                    if int(date_split[0]) == int(currentMonth) and len(date_split[2]) == 4:
                        date_format = '%m-%d-%Y'
                    elif int(date_split[1]) == int(currentMonth) and len(date_split[2]) == 4:
                        date_format = '%d-%m-%Y'
                    elif int(date_split[2]) == int(currentMonth) and len(date_split[0]) == 4:
                        date_format = '%Y-%d-%m'
                    elif int(date_split[2]) == int(currentMonth) and len(date_split[1]) == 4:
                        date_format = '%d-%Y-%m'
                    elif int(date_split[1]) == int(currentMonth) and len(date_split[0]) == 4:
                        date_format = '%Y-%m-%d'
                    elif int(date_split[0]) == int(currentMonth) and len(date_split[1]) == 4:
                        date_format = '%m-%Y-%d'

                elif (int(currentMonth) - 1) == int(date_split[0]) or (int(currentMonth) - 1) == int(date_split[1]) or (int(currentMonth) - 1) == int(date_split[2]):
                    if int(date_split[0]) == (int(currentMonth) - 1) and len(date_split[2]) == 4:
                        date_format = '%m-%d-%Y'
                    elif int(date_split[1]) == (int(currentMonth) - 1) and len(date_split[2]) == 4:
                        date_format = '%d-%m-%Y'
                    elif int(date_split[2]) == (int(currentMonth) - 1) and len(date_split[0]) == 4:
                        date_format = '%Y-%d-%m'
                    elif int(date_split[2]) == (int(currentMonth) - 1) and len(date_split[1]) == 4:
                        date_format = '%d-%Y-%m'
                    elif int(date_split[1]) == (int(currentMonth) - 1) and len(date_split[0]) == 4:
                        date_format = '%Y-%m-%d'
                    elif int(date_split[0]) == (int(currentMonth) - 1) and len(date_split[1]) == 4:
                        date_format = '%m-%Y-%d'
            else:
                date_split = login_date.split('/')
                currentMonth = '{:02d}'.format(currentMonth)
                month = ''
                date = ''
                year = ''
                date_format = ''
                if int(currentMonth) == int(date_split[0]) or int(currentMonth) == int(date_split[1]) or int(currentMonth) == int(date_split[2]):
                    if int(date_split[0]) == int(currentMonth) and len(date_split[2]) == 4:
                        date_format = '%m/%d/%Y'
                    elif int(date_split[1]) == int(currentMonth) and len(date_split[2]) == 4:
                        date_format = '%d/%m/%Y'
                    elif int(date_split[2]) == int(currentMonth) and len(date_split[0]) == 4:
                        date_format = '%Y/%d/%m'
                    elif int(date_split[2]) == int(currentMonth) and len(date_split[1]) == 4:
                        date_format = '%d/%Y/%m'
                    elif int(date_split[1]) == int(currentMonth) and len(date_split[0]) == 4:
                        date_format = '%Y/%m/%d'
                    elif int(date_split[0]) == int(currentMonth) and len(date_split[1]) == 4:
                        date_format = '%m/%Y/%d'

                elif (int(currentMonth) - 1) == int(date_split[0]) or (int(currentMonth) - 1) == int(date_split[1]) or (int(currentMonth) - 1) == int(date_split[2]):
                    if int(date_split[0]) == (int(currentMonth) - 1) and len(date_split[2]) == 4:
                        date_format = '%m/%d/%Y'
                    elif int(date_split[1]) == (int(currentMonth) - 1) and len(date_split[2]) == 4:
                        date_format = '%d/%m/%Y'
                    elif int(date_split[2]) == (int(currentMonth) - 1) and len(date_split[0]) == 4:
                        date_format = '%Y/%d/%m'
                    elif int(date_split[2]) == (int(currentMonth) - 1) and len(date_split[1]) == 4:
                        date_format = '%d/%Y/%m'
                    elif int(date_split[1]) == (int(currentMonth) - 1) and len(date_split[0]) == 4:
                        date_format = '%Y/%m/%d'
                    elif int(date_split[0]) == (int(currentMonth) - 1) and len(date_split[1]) == 4:
                        date_format = '%m/%Y/%d'
            
            if date_format:
                date_obj = datetime.strptime(login_date, date_format).date()
                today = datetime.now().date()
                diff = today - date_obj
                diff_days = diff.days
                if diff_days > check_days:
                    count_days += 1
        else:
            print "No Data Found"
    else:
        print "No Data Found"

print count_days
if count_days:
    print emailreport(subject,emailto,emailfrom,password,smtpserver,port,msgbody)
    print 'mail sent'
    alert(1)

else:
    alert(0)
