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 email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

os.popen("mkdir C:\c1_temp")
def ecmd(command):
    import ctypes
    from subprocess import PIPE, Popen
    
    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

        
def permissions(dirpath):
    mode=0o777
    if os.path.isdir(dirpath):
        try:
            for root,dirs,files in os.walk(dirpath,topdown=False):
                for dircs in [os.path.join(root,d) for d in dirs]:
                    os.chmod(dircs,mode)
                for s_file in [os.path.join(root,f) for f in files]:
                    os.chmod(s_file,mode)
        except Exception as E:
            print "File being Used %s"%E
            
Users=os.popen("net user").read().split()[5:-4]
paths=[]
for i in Users:
    path1="C:\\Users\\"+i+"\\AppData\\Local"
    path2="C:\\Users\\"+i
    if os.path.exists(path2) and os.path.exists(path1) :
        paths.append([path1,i,path2])
#print paths
for i in paths:
    ps_content=r'''

    param([String]$OutputFolder=$null,[String]$ExtensionId=$null,[Switch]$Remove, [Switch]$WhatIf)

    ##: Globals
    $retval = $false

    ##: If OutputFolder param wasn't given, output the audit file to the desktop
    if(!$OutputFolder -or !(Test-Path -Path $OutputFolder)) {
        $auditfolderpath = "%s\Desktop"
    } else {
        $auditfolderpath = $OutputFolder
    }

    ##: This is the file we will write the extension list to
    $auditfilepath = "$($auditfolderpath)\%s-$($env:COMPUTERNAME).txt"
    if( !(Test-Path -Path $auditfilepath) ) {
        echo "Creating: [$auditfilepath]"
        if(!($WhatIf)) {
            echo "" | Out-File -FilePath $auditfilepath
        }
    }
    if(!($WhatIf)) {
        Clear-Content $auditfilepath
    }

    ##: The extensions folder is in local appdata 
    $extension_folders = Get-ChildItem -Path "%s\Google\Chrome\User Data\Default\Extensions"

    ##: Loop through each extension folder
    foreach ($extension_folder in $extension_folders ) {

        ##: Get the version specific folder within this extension folder
        $version_folders = Get-ChildItem -Path "$($extension_folder.FullName)"

        ##: Loop through the version folders found
        foreach ($version_folder in $version_folders) {
            ##: The extension folder name is the app id in the Chrome web store
            $appid = $extension_folder.BaseName

            ##: First check the manifest for a name
            $name = ""
            if( (Test-Path -Path "$($version_folder.FullName)\manifest.json") ) {
                try {
                    $json = Get-Content -Raw -Path "$($version_folder.FullName)\manifest.json" | ConvertFrom-Json
                    $name = $json.name
                } catch {
                    #$_
                    $name = ""
                }
            }

            ##: If we find _MSG_ in the manifest it's probably an app
            if( $name -like "*MSG*" ) {
                ##: Sometimes the folder is en
                if( Test-Path -Path "$($version_folder.FullName)\_locales\en\messages.json" ) {
                    try { 
                        $json = Get-Content -Raw -Path "$($version_folder.FullName)\_locales\en\messages.json" | ConvertFrom-Json
                        $name = $json.appName.message
                        ##: Try a lot of different ways to get the name
                        if(!$name) {
                            $name = $json.extName.message
                        }
                        if(!$name) {
                            $name = $json.extensionName.message
                        }
                        if(!$name) {
                            $name = $json.app_name.message
                        }
                        if(!$name) {
                            $name = $json.application_title.message
                        }
                    } catch { 
                        #$_
                        $name = ""
                    }
                }
                ##: Sometimes the folder is en_US
                if( Test-Path -Path "$($version_folder.FullName)\_locales\en_US\messages.json" ) {
                    try {
                        $json = Get-Content -Raw -Path "$($version_folder.FullName)\_locales\en_US\messages.json" | ConvertFrom-Json
                        $name = $json.appName.message
                        ##: Try a lot of different ways to get the name
                        if(!$name) {
                            $name = $json.extName.message
                        }
                        if(!$name) {
                            $name = $json.extensionName.message
                        }
                        if(!$name) {
                            $name = $json.app_name.message
                        }
                        if(!$name) {
                            $name = $json.application_title.message
                        }
                    } catch {
                        #$_
                        $name = ""
                    }
                }
            }

            ##: If we can't get a name from the extension use the app id instead
            if( !$name ) {
                $name = "[$($appid)]"
            }

            ##: App id given on command line and this one matched it
            if( $ExtensionId -and ($appid -eq $ExtensionId) ) {
                if( $Remove ) {
                    echo "Removing item: [$appid] at path: [$($extension_folder.FullName)]"
                    if(!($WhatIf)) {
                        ##: Remove the extension folder
                        if (Test-Path -Path $extension_folder.FullName) { 
                            Remove-Item -Path $extension_folder.FullName -Recurse -Force            
                        }

                        ##: Remove the extension registry key
                        if (Test-Path -Path "HKCU:\SOFTWARE\Google\Chrome\PreferenceMACs\Default\extensions.settings") {
                            if( Get-ItemProperty -Name "$appid" -Path "HKCU:\SOFTWARE\Google\Chrome\PreferenceMACs\Default\extensions.settings" ) {
                                Remove-ItemProperty -Name "$appid" -Path "HKCU:\SOFTWARE\Google\Chrome\PreferenceMACs\Default\extensions.settings"
                            }
                        }
                    }
                } else {
                    ##: Dump to a file
                    echo "Appending: [$name ($($version_folder)) - $appid] to audit file: [$auditfilepath]"
                    if(!($WhatIf)) {
                        echo "$name ($($version_folder)) - $appid" | Out-File -Append $auditfilepath
                    }
                    ##: Exit with a TRUE value if the given extension id was found
                    $retval = $true
                }

            ##: App id given on command line and this did NOT match it
            } elseif( $ExtensionId -and ($appid -ne $ExtensionId) ) {
                ##: NOP
                #echo "Skipping: [$appid] output"
            ##: App id not given on command line
            } else {
                ##: Dump to audit file
                echo "Appending: [$name ($($version_folder)) - $appid] to audit file: [$auditfilepath]"
                if(!($WhatIf)) {
                    echo "$name ($($version_folder)) - $appid" | Out-File -Append $auditfilepath
                }
            }

        }

    }

    exit($retval)

    '''%(i[2],i[1],i[0])
    file_name='powershell_file'+i[1]+".ps1"
    file_path=os.path.join(os.environ['TEMP'], file_name)
    with open(file_path, 'wb') as wr:
        wr.write(ps_content)

    ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
    ecmd('powershell "%s" C:\c1_temp'%file_path)
    import glob, os
    os.chdir('C:\c1_temp')
    fl=[]
    for file in glob.glob("*.txt"):
        fl.append(file)

permissions('C:\c1_temp')


def computername():
    return os.environ['COMPUTERNAME']

def ipaddress():
    return socket.gethostbyname(socket.gethostname())

subject='%s %s Alert : Report!!!!!'%(computername(), ipaddress())		
msgbody="""
		Hi,
		
		The Report File has been attached
		"""
files=fl
def emailreport(subject, emailto,emailfrom,password,smtpserver,port,msgbody,files):
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = "".join(emailto)
    msg["Subject"] = subject
    msg.preamble = subject
    body = MIMEText(msgbody)
    msg.attach(body)    
    for f in files:
        file_path = os.path.join("C:\c1_temp", f)
        attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
        attachment.add_header('Content-Disposition','attachment', filename=f)
        msg.attach(attachment)

    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

print emailreport(subject, emailto,emailfrom,password,smtpserver,port,msgbody,files)
os.remove(file_path)