no=15        #Edit the xx parameter as Device Timeout. Eg if you have 500 enrolled endpoints then that xx must "100".
Head_computer=r'CHANGE ME' # Head computer to send the email 
emailto='XXXXX@YYYY.COM' # Email address to send the report 
Head_computer=Head_computer.upper()
KI=list(Head_computer)
KI.insert(0,str(no))
import datetime
KI.insert(len(KI),datetime.datetime.now().strftime("%Y%m%d"))
KEY="".join(KI)
import ast
import threading
import time
import os
from subprocess import PIPE, Popen
import ctypes
import shutil
def Email(fileToSend,To):
    from mailjet_rest import Client
    import os
    api_key='3e70858a7a5c5fbc245a662d5d9aa238'   # API KEY of Mail Jet 
    api_secret= 'a337abcc84d8fb062f6f1597d966ae6f'  # API SECRET KEY of Mail Jet
    mailjet = Client(auth=(api_key, api_secret), version='v3.1')
    import base64
    with open(fileToSend, 'rb') as fp:
        ki=base64.b64encode(fp.read())
    data = {
      'Messages': [
                    {
                            "From": {
                                    "Email": "c1operations123@gmail.com",
                            },
                            "To": [
                                    {
                                            "Email": "%s"%To,
                                    }
                            ],
                            "Subject": "Virus Database version of all devices ",
                            "TextPart": "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
                            "HTMLPart": """<h3> Hi \n

        Please find the attachment which contains all the device reports \n

        Thank you.</h3>""",
                            "Attachments": [
                                    {
                                            "ContentType": "text/csv",
                                            "Filename": "Finalreport.csv",
                                            "Base64Content": "%s"%ki
                                    }
                            ]
                    }
            ]
    }
    result = mailjet.send.create(data=data)
    ret=result.status_code
    if ret==200:
        out=result.json()
        out=str(out)
        if "success" in out:
            print "Email Sent Successfully"
    else:
        print "Error sending email"
def Download(URL, DownloadTo = None, FileName = None):
    import urllib
    import ssl
    if FileName:
        FileName = FileName
    else:
        FileName = URL.split('/')[-1]
        
    if DownloadTo:
        DownloadTo = DownloadTo
    else:
        DownloadTo = os.path.join(os.environ['TEMP'])
        
    DF = os.path.join(DownloadTo, FileName)
    with open(os.path.join(DownloadTo, FileName), 'wb') as f:
        try:
            context = ssl._create_unverified_context()
            f.write(urllib.urlopen(URL,context=context).read())
        except:
            f.write(urllib.urlopen(URL).read())
    if os.path.isfile(DF):
        return DF
    else:
        return False
def zip_item(path,final_path):  # Creating ZIP file
    import zipfile
    zip_ref = zipfile.ZipFile(path, 'r')
    zip_ref.extractall(final_path)
    zip_ref.close()
    return final_path
def Import_pubnub(DEST):
    BDPATH = Download(r'https://drive.google.com/uc?export=download&id=1R1KFmrC0jh6TOdCFePt2SNTbu_ti_CpP', FileName = 'PUBNUB.zip')
    SRC = os.path.join(os.environ['TEMP'])
    path=zip_item(BDPATH,SRC)
    SRC = os.path.join(os.environ['TEMP'],'PUBNUB')
    from distutils.dir_util import copy_tree
    copy_tree(SRC, DEST)
    import pubnub 
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    print "Pubnub is imported"
    return DEST
import os
import subprocess
import shutil,urllib2,time
from subprocess import PIPE, Popen
import socket
import smtplib
import mimetypes
import ctypes
import _winreg
import os.path

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)
            

def computername():
    return os.environ['COMPUTERNAME']
def ipaddress():
    return socket.gethostbyname(socket.gethostname())
def virus_database_Version():
    import os
    try:
        d=os.listdir('C:\ProgramData\Comodo\Cis\signatures')
        for f in d:
            return f.strip('b.cav')
    except Exception as err: 
            return None
def Database_Update_status():
    import os
    import os.path, time
    try:
        Modified_time = os.path.getmtime('C:\ProgramData\Comodo\Cis\signatures')
        Current_time=time.time()
        Diff=Current_time-Modified_time
        if(Diff<86400):
            return "Database Updated within 24 hrs"
        else:
            return "Database has not been Updated for last 24 hrs"
    except Exception as err:
        return None
    
def print_Report(KEY):
            #data={'Name':computername(), 'IP':ipaddress(), 'DatabaseVers':virus_database_Version(), 'Status':Database_Update_status()}
            data=[KEY,computername(),ipaddress(),virus_database_Version(),Database_Update_status()]
            print data
            return data

list_head=['Computer_Name', 'IP_Address',"Virus_Database_Version","Virus_Database_status"]

def publish_nonhead():
    import time    
    time.sleep(30)
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    publish_key1= 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1= 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'
     
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True
     
    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:
		
        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(print_Report(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
            print e

def publish(no):
    import pubnub 
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    publish_key1= 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1= 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'
     
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True
     
    pubnub = PubNub(pnconfig)
    import time
    s=3*no
    time.sleep(s)  


    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(print_Report(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
        
        app_process=os.getpid()
        app_process=str(app_process)
        import subprocess;
        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)

        time.sleep(5)
        reportfolder=os.path.join(os.environ['ProgramData'],"new.csv")
        Email(reportfolder,emailto)
        print "Your file is in head computer at "+reportfolder 
        with disable_file_system_redirection():
            process=subprocess.Popen(['taskkill', '/F','/PID',app_process],shell=True,stdout=subprocess.PIPE);
            result=process.communicate()[0]
            print (result)
    except PubNubException as e:
            print e


class LongFunctionInside(object):
    lock_state = threading.Lock()
    working = False

    def long_function(self, timeout,no):

        self.working = True

        timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout,))
        timeout_work.setDaemon(True)
        timeout_work.start()
        import logging

        import pubnub
        from pubnub.exceptions import PubNubException
        from pubnub.pnconfiguration import PNConfiguration
        from pubnub.pubnub import PubNub, SubscribeListener

        import time
        import os
        pnconfig = PNConfiguration()
         
        pnconfig.subscribe_key = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'
        pnconfig.publish_key = ''

        pubnub = PubNub(pnconfig)
        n=0
        my_listener = SubscribeListener()

        pubnub.subscribe().channels('Channel-706fxzjkv').execute()
        fp=os.path.join(os.environ['ProgramData'],"new.csv")
        sample=''
        for i in list_head:
            if i == None:
                sample=sample+"None"+","
            else:
                sample=sample+i+","
        with open(fp,'w') as f:
            f.write(sample)
            f.write('\n')
        while True:
            print "Listening..."# endless/long work
            pubnub.add_listener(my_listener)
            result = my_listener.wait_for_message_on('Channel-706fxzjkv')
            pubnub.remove_listener(my_listener)
            result=result.message
            print result[0]
            sample=""
            if(result[0]==KEY):
                with open(fp,'a+') as f:
                    for i in range(1,len(result)):
                        if result[i] == None:
                            sample=sample+"None"+","
                        else:
                            sample=sample+result[i]+","
                    f.write(sample)                   
                    f.write('\n')
            if not self.working:  # if state is working == true still working
                break
        self.set_state(True)

    def work_time(self, sleep_time):
        print sleep_time# thread function that just sleeping specified time,
        
        time.sleep(sleep_time)
        if self.working:
            publish(no)            
            self.set_state(False)

    def set_state(self, state):  # secured state change
        while True:
            self.lock_state.acquire()
            try:
                self.working = state
                break
            finally:
                self.lock_state.release()

HOMEPATH = r"C:\Program Files (x86)"
if os.path.exists(HOMEPATH):
        HOMEPATH = r"C:\Program Files (x86)"
else:
    HOMEPATH =r"C:\Program Files"
fp=os.path.join(os.environ['ProgramData'],"new.csv")
if os.path.exists(fp):
	try:
		os.remove(fp)
	except:
		pass

DEST= os.path.join(HOMEPATH,r'COMODO\Comodo ITSM\Lib\site-packages')
Folders=os.listdir(DEST)
Nodow=0
Del_folders=['certifi', 'certifi-2018.1.18.dist-info','chardet', 'chardet-3.0.4.dist-info', 'Cryptodome', 'pubnub', 'pubnub-4.0.13.dist-info', 'pycryptodomex-3.4.12.dist-info','requests']
for i in Del_folders:
    if i in Folders:
        Nodow=Nodow+1
if Nodow>7:
    c=0
else:
    DEST=Import_pubnub(DEST)
computer=os.environ['computername']
import os
with disable_file_system_redirection():
    chk=os.popen('wmic product get name').read()
    if computer==Head_computer :
                lw = LongFunctionInside()
                lw.long_function(0.1,no)
                
    if 'COMODO Client - Security' in chk:
        publish_nonhead()
        
    else:
        print 'COMODO Client - Security is not Installed'
