#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
emailto=itsm.getParameter('EmailTo')  ## Provide an Toemail address where the mail need to be sent.You can also provide any number of To eamil address For example: ['varun@yopmail.com', xxxx@yopmail.com]
emailfrom=itsm.getParameter('EmailFrom')  ## Provide the From Email address from which the mail to be send
password=itsm.getParameter('Password')               ##Provide password for from email
smtpserver='smtp.gmail.com'
port=587

import os,sys,shutil,re,sys,socket,_winreg,random,getpass
from datetime import date, datetime
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
import ctypes
from subprocess import PIPE, Popen

def computername():
    return os.environ['COMPUTERNAME']

def ipaddress():
    return socket.gethostbyname(socket.gethostname())

subject='%s %s Alert : Operating System Licencing and Hardware Information Reports!!!!!'%(computername(), ipaddress())		

def emailreport(subject, emailto,emailfrom,password,smtpserver,port,fileToSend):
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ",".join(emailto)
    msg["Subject"] = subject
    msg.preamble = subject  
    for file in fileToSend:
        with open(file) as fp:
            record = MIMEBase('application', 'octet-stream')
            record.set_payload(fp.read())
            encoders.encode_base64(record)
            record.add_header('Content-Disposition', 'attachment',
            filename=os.path.basename(file))
            msg.attach(record)
    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

import os;
import re;
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)

tmp = os.environ['TEMP']
filepath = tmp+'\\'+r'GetProductKey.vbs'

decodekey ="""
Set wshShell = CreateObject("Wscript.Shell")
WScript.Echo ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"))
Function ConvertToKey(Key)
Const KeyOffset = 52
i = 28
Chars = "BCDFGHJKMPQRTVWXY2346789"
Do
Cur = 0
x = 14
Do
Cur = Cur * 256
Cur = Key(x + KeyOffset) + Cur
Key(x + KeyOffset) = (Cur \ 24) And 255
Cur = Cur Mod 24
x = x -1
Loop While x >= 0
i = i -1
KeyOutput = Mid(Chars, Cur + 1, 1) & KeyOutput
If (((29 - i) Mod 6) = 0) And (i <> -1) Then
i = i -1
KeyOutput = "-" & KeyOutput
End If
Loop While i >= 0
ConvertToKey = KeyOutput
End Function"""

with disable_file_system_redirection():
    with open (filepath,'w+') as obj:
        obj.write(decodekey)
    os.chdir(tmp)
    a=os.getcwd()
    GetKey = os.popen("cscript.exe GetProductKey.vbs").read()
    regex = r"([A-Za-z0-9]{5}-[A-Za-z0-9]{5}-[A-Za-z0-9]{5}-[A-Za-z0-9]{5}-[A-Za-z0-9]{5})"
    result = re.findall(regex,GetKey)
    guid_digital_key=os.popen('cscript C:\Windows\System32\slmgr.vbs /dlv').read();
    os.remove("GetProductKey.vbs")
    guid=os.popen('cscript C:\Windows\System32\slmgr.vbs /dlv').read();
    os_details = os.popen('systeminfo | findstr /B /C:"OS "').read()

data = ''
	
if "License Status: Notification" in guid:
    data += guid.replace('License Status: Notification','License Status: Windows is not activated');
elif "License Status: Out-Of-Box Grace Period" in guid:
    data += guid.replace('License Status: Out-Of-Box Grace Period','License Status: Windows is not activated')
elif "License Status: Out-Of-Tolerance Grace Period" in guid :
    data += guid.replace('License Status: Out-Of-Tolerance Grace Period','License Status: Windows is not activated')
elif "License Status: Non-Genuine Grace Period" in guid:
    data += guid.replace('License Status: Non-Genuine Grace Period','License Status: Windows is not activated')
elif 'License Status: Extended Grace' in guid:
    data += guid.replace('License Status: Extended Grace','License Status: Windows is not activated')
elif 'License Status: Unlicensed' in guid:
    data += guid.replace('License Status: Unlicensed','License Status: Windows is not activated')
elif "License Status: Licensed" in guid:
    data += guid
else:
    data += guid

data += "\n"

data += "The Digital Product ID is : " +result[0]
data += "                                                                                                 "
data += "\n"
data += "Information on Operating System"
data += "\n"
data += os_details
data += "\n"
with open(r"C:\ProgramData\os_licensing.txt","w")as out:
    out.write(data)
	
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
		
motherboard = ecmd(r'wmic baseboard get product,Manufacturer')
memory_size = ecmd(r'wmic MemoryChip get Capacity')
if memory_size:
    memory_size = memory_size.split()[1]
    memory_size = str(int(memory_size) / 1073741824)
hd_size = ecmd(r'wmic logicaldisk get Size')
if hd_size:
    hd_size = hd_size.split()[1]
    hd_size = str(int(hd_size) / 1073741824)
network = ecmd(r'ipconfig')
data1 = ''
data1 += "\n**********************************************"
data1 += "\n************** Hardware Information ***************************"
data1 += "\n**********************************************\n"
data1 += "\n****************** Motherboard Information ******************\n"
data1 += "\n**********************************************\n"
data1 += motherboard
data1 += "\n"
data1 += "\n**********************************************\n"
data1 += "Memory Size:    "+memory_size+' GB'
data1 += "\n"
data1 += "Hard Disk Size:    "+hd_size+' GB'
data1 += "\n"
data1 += "\n**********************************************\n"
data1 += "\n****************** Network Information ******************\n"
data1 += "\n**********************************************\n"
data1 += network

with open(r"C:\ProgramData\hardware_information.txt","w")as out1:
    out1.write(data1)

fileToSend = ['C:\ProgramData\os_licensing.txt','C:\ProgramData\hardware_information.txt']
print emailreport(subject,emailto,emailfrom,password,smtpserver,port,fileToSend)
