## Choose your choice whether you want to send email or print the report on ITSM ## sendmail can be set as 1 or 0 ## if sendmail is 1 then report will be delivered to your email id and please don't forgot to set your email address and further request - All categories are delivered to your email address ## if sendmail is 0 then your report is displayed in the ITSM console - Limited categories only sendmail=1 emailto=['email1@domain.com', 'email2@domain.com', 'email3@domain.com'] emailfrom='your_email_id@your_domain.com' password='password' smtpserver='smtp.gmail.com' port=587 ## Hardware Inventory def computername(): import os return os.environ['COMPUTERNAME'] def ipaddress(): import socket return socket.gethostbyname(socket.gethostname()) def ExecuteCMD(CMD, OUT=False): 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) from subprocess import PIPE, Popen with disable_file_system_redirection(): OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE) out, err = OBJ.communicate() RET = OBJ.returncode if RET==0: if OUT: if out: return out.strip() return True return True return False def DNDS(rtkey, pK, kA): import os import _winreg ln = [] lv = [] try: oK = _winreg.OpenKey(rtkey, pK, 0, kA) i = 0 while True: try: bkey = _winreg.EnumKey(oK, i) vkey = os.path.join(pK, bkey) oK1 = _winreg.OpenKey(rtkey, vkey, 0, kA) try: tls = [] DN, bla = _winreg.QueryValueEx(oK1, 'DisplayName') DV, bla = _winreg.QueryValueEx(oK1, 'DisplayVersion') _winreg.CloseKey(oK1) ln.append(DN) lv.append(DV) except: pass i += 1 except: break _winreg.CloseKey(oK) return zip(ln, lv) except: return zip(ln, lv) def swlist(): import _winreg rK = _winreg.HKEY_LOCAL_MACHINE sK = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' openedKey = _winreg.OpenKey(rK, sK, 0, _winreg.KEY_READ) arch, bla = _winreg.QueryValueEx(openedKey, 'PROCESSOR_ARCHITECTURE') arch = str(arch) _winreg.CloseKey(openedKey) if arch == 'AMD64': fList = DNDS(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ) fList.extend(DNDS(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ)) fList.extend(DNDS(_winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft1\Windows\CurrentVersion\Uninstall', _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ)) fList.extend(DNDS(_winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft1\Windows\CurrentVersion\Uninstall', _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ)) else: fList = DNDS(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', _winreg.KEY_READ) fList.extend(DNDS(_winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', _winreg.KEY_READ)) fList = set(fList) return fList def filename(): import random filename=random.choice(['QAZ', 'WSX', 'EDC', 'RFV', 'TGB', 'YHN', 'UJM', 'IKO', 'LPQ', 'qaz', 'wsx', 'edc', 'rfv', 'tgb', 'yhn', 'ujm', 'iko', 'lpq'])+str(random.randint(2000,10000)) return filename def filenfo(filename): import os filenfo=os.path.join(os.environ['TEMP'], filename+'.nfo') return filenfo def emailreport(subject, emailto,emailfrom,fileToSend,password,smtpserver,port,msgbody): 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 os msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = ",".join(emailto) msg["Subject"] = subject msg.preamble = subject body = MIMEText(msgbody) msg.attach(body) for i in fileToSend: with open(i) 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(i)) 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 "CSV report has been sent to "+msg["To"] except Exception as E: return E if sendmail==1: import os from xml.etree import ElementTree filename=filename() filenfo=filenfo(filename) ExecuteCMD('msinfo32 /nfo '+filenfo) with open(filenfo, 'rt') as f: tree=ElementTree.parse(f) file1csv=os.path.join(os.environ['TEMP'], computername()+ipaddress()+'SI'+filename+'.csv') filecsv=os.path.join(os.environ['TEMP'], computername()+ipaddress()+'HI'+filename+'.csv') j=1 with open(file1csv, 'w') as f: f.write('S.No.|Software Name|Version Details\n') for i in sorted(swlist()): a, b = i try: f.write(str(j)+'|'+str(a)+'|'+str(b)+'\n') except: f.write(str(j)+'|'+str(a.encode('utf-8'))+'|'+str(b.encode('utf-8'))+'\n') j+=1 list=['System Summary','Hardware Resources', 'Conflicts/Sharing', 'DMA', 'Forced Hardware', 'I/O', 'IRQs', 'Memory', 'Components', 'Multimedia', 'Audio Codecs', 'Video Codecs', 'CD-ROM', 'Sound Device', 'Display', 'Infrared', 'Input', 'Keyboard', 'Pointing Device', 'Modem', 'Network', 'Adapter', 'Protocol', 'WinSock', 'Ports', 'Serial', 'Parallel', 'Storage', 'Drives', 'Disks', 'SCSI', 'IDE', 'Printing', 'Problem Devices', 'USB', 'Software Environment', 'System Drivers', 'Environment Variables', 'Print Jobs', 'Network Connections', 'Running Tasks', 'Loaded Modules', 'Services', 'Program Groups', 'Startup Programs', 'OLE Registration', 'Windows Error Reporting'] with open(filecsv, 'a') as f1: for node in tree.iter('Category'): if node.attrib['name'] in list: f1.write(node.attrib['name']+'\n') c=0 for n in node.getchildren(): if n!=[]: string='' title='' for i in n.getchildren(): if c==0: title+=i.tag+'|' if i.text!='\n': try: string+=str(i.text)+'|' except: string+=(i.text).encode('utf-8')+'|' if c==0: f1.write(title[:-1]+'\n') if string!='\n': f1.write(string[:-1]+'\n') c+=1 msgbody=r'''Hello, Please find the attachments for the CSV report of Hardware and Software Inventory %s [for Hardware Inventory] %s [for Software Inventory] Thank you.'''%(filecsv.split(os.sep)[-1], file1csv.split(os.sep)[-1]) print emailreport('CSV REPORT of '+computername()+'-'+ipaddress(), emailto, emailfrom, [filecsv, file1csv], password, smtpserver, port, msgbody) os.remove(filenfo) os.remove(file1csv) os.remove(filecsv) else: import os from xml.etree import ElementTree filename=filename() filenfo=filenfo(filename) ExecuteCMD('msinfo32 /nfo '+filenfo) with open(filenfo, 'rt') as f: tree=ElementTree.parse(f) k=1 print '{:20}{}'.format('Computer Name',computername()) print '{:20}{}'.format('IP Address', ipaddress()) print '='*20+' Software Inventory '+'='*20 print '{:<3} {:<100} {:>18}'.format('S.No.', 'Software Name', 'Version Details') for i in sorted(swlist()): a, b = i try: print '{:<3} {:<100} {:>20}'.format(k, a.encode('utf-8'), b.encode('utf-8')) except: print k, a, b k+=1 list=['System Summary','Hardware Resources', 'Conflicts/Sharing', 'DMA', 'Forced Hardware', 'I/O', 'IRQs', 'Memory', 'Components', 'Multimedia', 'Audio Codecs', 'Video Codecs', 'CD-ROM', 'Sound Device', 'Display', 'Infrared', 'Input', 'Keyboard', 'Pointing Device', 'Modem', 'Network', 'Adapter', 'Protocol', 'WinSock', 'Ports', 'Serial', 'Parallel', 'Storage', 'Drives', 'Disks', 'SCSI', 'IDE', 'Printing', 'Problem Devices', 'USB', 'Software Environment', 'System Drivers', 'Environment Variables', 'Print Jobs', 'Network Connections', 'Running Tasks', 'Loaded Modules', 'Services', 'Program Groups', 'Startup Programs'] print '\n\n' print '='*20+' Hardware Inventory '+'='*20 for node in tree.iter('Category'): if node.attrib['name'] in list: print '\n' print node.attrib['name'] print '_'*len(node.attrib['name']) for n in node.getchildren(): if n!=[]: string='' for i in n.getchildren(): if i.text!='\n': try: string+='{:20}{}\n'.format(str(i.tag), str(i.text)) except: string+='{:20}{}\n'.format(str(i.tag), str((i.text).encode('utf-8'))) if string!='\n': print string os.remove(filenfo)