import time
import ctypes
from subprocess import Popen,PIPE
import re
import os
import sys
start=time.time()

def alert(arg):
    sys.stderr.write("%d%d%d" % (arg, arg, arg))
    
cmd1=r'WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get "displayName"'
hostnme=os.popen("hostname").read().strip()
with open(r"C:\Program Files (x86)\ITarian\Endpoint Manager\rmmlogs\RmmService.log","r") as r:
    meta_data=r.read()
itsm_fullpath=re.findall(r"https.*log",meta_data)[0]

    
def cmdrun(cmd,itsm_fullpath):
    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():
        hostnme=os.popen("hostname").read().strip()
        obj=Popen(cmd,stdout=PIPE,stderr=PIPE)
        res,err=obj.communicate()
        if err:
            print err
        else:
            c=[i.strip()  for i in res.strip().splitlines()[2:] if i not in ["Windows Defender"," "]]
            #print c
            if len(c)==0:
                print "Alert for %s : No Anti-Virus software is present on this host."%hostnme
                print "Link to %s in ITarian Endpoint Manager: %s"%(hostnme,itsm_fullpath)
                return alert(1)
            else:
                print "Anti-Virus software is present on this host %s."%hostnme
                print "Link to %s in ITarian Endpoint Manager: %s"%(hostnme,itsm_fullpath)
                return alert(0)
cmdrun(cmd1,itsm_fullpath)   

end=time.time()
print("Execution Time: {}".format(end-start))