示例#1
0
def getOcsDebugLog(xmlString):

    xmlFile = xml.dom.minidom.parseString(xmlString)
    userDomaine = xmlFile.getElementsByTagName(
        "USERDOMAIN")[0].firstChild.nodeValue
    ocsFolder = Pulse2InventoryProxyConfig().command_name
    i = len(ocsFolder)
    found = False
    while not found and i > 0:
        found = (ocsFolder[i - 1] == '\\')
        i -= 1

    if found:
        logFile = open(ocsFolder[0:i + 1] + userDomaine + ".log", "r")
        logFileString = logFile.read()
        logFile.close()
    else:
        logFileString = "Error : couldn't open Log File"

    newnode = xmlFile.createElement("OCSDEBUG")
    newsubnode = xmlFile.createElement("DEBUGLOG")
    newtext = xmlFile.createTextNode(logFileString)
    refnode = xmlFile.getElementsByTagName("CONTENT")[0]
    #Optional : help to the final xml File can be esay read
    newsubnode.appendChild(newtext)
    newnode.appendChild(xmlFile.createTextNode("\n"))
    newnode.appendChild(newsubnode)
    newnode.appendChild(xmlFile.createTextNode("\n"))
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    xmlString = xmlFile.toxml("utf-8")
    return xmlString
示例#2
0
def improveXML(xmlFileString):

    xmlFileString = xmlUpdate(xmlFileString, informationSearch())
    if Pulse2InventoryProxyConfig().savexmlmodified:
        filout = open('XmlOutput.xml', 'w')
        for i in xmlFileString:
            filout.write(i)
        filout.close()

    return xmlFileString
示例#3
0
def handler(signum, frame):
    """
    SIGTERM handler
    """
    os.seteuid(0)
    os.setegid(0)
    try:
        os.unlink(Pulse2InventoryProxyConfig().pidfile)
    except OSError:
        pass

    sys.exit(0)
 def init(self):
     config = Pulse2InventoryProxyConfig()
     config.setup(self.inifile)
     logging.config.fileConfig(self.inifile)
     initialize(config)
示例#5
0
def xmlUpdate(xmlString, lastInformation):

    xmlFile = xml.dom.minidom.parseString(xmlString)

    # Check Serial number between Ocs and WMI
    ssn = xmlFile.getElementsByTagName("SSN")[0].childNodes[0].nodeValue
    if (len(lastInformation['serialNumber']) > 0
            and ssn != lastInformation['serialNumber']):
        ssn = lastInformation['serialNumber']

    # Operating system installation date
    newnode = xmlFile.createElement("INSTALLDATE")
    newtext = xmlFile.createTextNode(lastInformation['installDate'])
    refnode = xmlFile.getElementsByTagName("OSVERSION")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    #Optionnal : help to the final xml File can be easy read
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # Company Register
    newnode = xmlFile.createElement("WINCOMPANY")
    newtext = xmlFile.createTextNode(lastInformation['companyRegister'])
    refnode = xmlFile.getElementsByTagName("WINOWNER")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # OS Architecture
    newnode = xmlFile.createElement("OSARCHITECTURE")
    newtext = xmlFile.createTextNode(lastInformation['osArchitecture'])
    refnode = xmlFile.getElementsByTagName("OSNAME")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # Last login Date
    newnode = xmlFile.createElement("DATELASTLOGGEDUSER")
    newtext = xmlFile.createTextNode(lastInformation['lastLogin'][1])
    refnode = xmlFile.getElementsByTagName("LASTLOGGEDUSER")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # Default Gateway
    newnode = xmlFile.createElement("DEFAULTGATEWAY")
    newtext = xmlFile.createTextNode(lastInformation['defaultGateway'])
    refnode = xmlFile.getElementsByTagName("HARDWARE")[0]

    newnode.appendChild(newtext)
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    # First boot date
    newnode = xmlFile.createElement("DATEFIRSTRUN")
    newtext = xmlFile.createTextNode(lastInformation['dateFirst'])
    refnode = xmlFile.getElementsByTagName("BIOS")[0]

    newnode.appendChild(newtext)
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    # Last boot date
    newnode = xmlFile.createElement("DATELASTRUN")
    newtext = xmlFile.createTextNode(lastInformation['dateLastBoot'])
    refnode = xmlFile.getElementsByTagName("BIOS")[0]

    newnode.appendChild(newtext)
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    # Who is Burner ?
    key = _winreg.OpenKey(
        _winreg.HKEY_CURRENT_USER,
        "Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\Drives")
    deviceKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                "System\MountedDevices\\")
    #Search the tag of all burner
    burner = []
    try:
        i = 0
        while True:
            keyname = _winreg.EnumKey(key, i)
            subkey = _winreg.OpenKey(
                _winreg.HKEY_CURRENT_USER,
                "Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\Drives\\"
                + keyname)
            if not (_winreg.QueryValueEx(subkey, "Drive Type")[0] == 3):
                burner.append(
                    _winreg.QueryValueEx(deviceKey, "\\??\\" + keyname)[0])

            _winreg.CloseKey(subkey)
            i = i + 1
    except WindowsError:  # pyflakes.ignore
        pass
    _winreg.CloseKey(key)

    #Add if the drive is burner
    for device in xmlFile.getElementsByTagName("DRIVES"):
        if device.getElementsByTagName(
                "TYPE")[0].firstChild.nodeValue == "CD-Rom Drive":
            isBurner = False
            newnode = xmlFile.createElement("BURNER")
            i = 0
            while i < len(burner) and not isBurner:
                #Compare the tag with the tag of DosDevices to found the letter device of the burner
                isBurner = (_winreg.QueryValueEx(
                    deviceKey,
                    "\\DosDevices\\" + device.getElementsByTagName("LETTER")
                    [0].firstChild.nodeValue[0] + ":")[0] == burner[i])
                if isBurner:
                    del burner[i]
                i += 1

            if isBurner:
                newtext = xmlFile.createTextNode("Burner")
            else:
                newtext = xmlFile.createTextNode("Only Reader")

            newnode.appendChild(newtext)
            device.appendChild(newnode)
            device.appendChild(xmlFile.createTextNode("\n"))

    _winreg.CloseKey(deviceKey)

    # Initializing Variable
    listSoftXML = xmlFile.getElementsByTagName("SOFTWARES")
    listSoftXMLDefault = xmlFile.getElementsByTagName("SOFTWARES")
    OSNAME = xmlFile.getElementsByTagName("OSNAME")[0].firstChild.nodeValue
    defaultNode = listSoftXMLDefault[0].cloneNode(1)
    key = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE,
        "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
    updateDetection = Pulse2InventoryProxyConfig().updatedetection

    try:
        i = 0
        while True:  #For every software in Uninstall Registry
            keyname = _winreg.EnumKey(key, i)
            subkey = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\\" +
                keyname)

            try:
                displayName = _winreg.QueryValueEx(subkey, "DisplayName")[0]
                nodeId = foundNodeInList(listSoftXML, "NAME", displayName)

                if nodeId != -1:
                    selectnode = listSoftXML[nodeId]
                    #del(listSoftXML[nodeId])       # Warning : Both key Registry can be exist for the same software.
                    # Drop used software can acelerat the improving
                    # but it can lost some information in two places.
                    #Type Package
                    newnode = xmlFile.createElement("FROM")
                    newtext = xmlFile.createTextNode('win')

                    newnode.appendChild(newtext)
                    selectnode.appendChild(newnode)
                    selectnode.appendChild(xmlFile.createTextNode("\n"))

                    #Software installation Date
                    try:
                        installDate = _winreg.QueryValueEx(
                            subkey, "InstallDate")[0]
                        installDate = windowsDateConversion(installDate, False)
                    except WindowsError:  # pyflakes.ignore
                        installDate = "N/A"

                    newnode = xmlFile.createElement("INSTALLDATE")
                    newtext = xmlFile.createTextNode(installDate)

                    newnode.appendChild(newtext)
                    selectnode.appendChild(newnode)
                    selectnode.appendChild(xmlFile.createTextNode("\n"))

                    # Version Check
                    try:
                        refnode = selectnode.getElementsByTagName(
                            "VERSION")[0].firstChild
                        if refnode.nodeValue == "N/A":
                            displayversion = _winreg.QueryValueEx(
                                subkey, "DisplayVersion")[0]
                            refnode.nodeValue = displayversion
                    except WindowsError:  # pyflakes.ignore
                        pass

                    # Software size calculated on hardDisk
                    try:
                        folder = _winreg.QueryValueEx(subkey,
                                                      "InstallLocation")[0]
                        if len(folder) > 0:
                            foldersize = sizeFolder(folder)
                            if not (foldersize > 0):
                                foldersize = "N/A"

                        else:
                            foldersize = "N/A"
                            newnode = xmlFile.createElement("FOLDER")
                            newtext = xmlFile.createTextNode("N/A")
                            refnode = selectnode.getElementsByTagName(
                                "VERSION")[0]

                            newnode.appendChild(newtext)
                            refnode.parentNode.insertBefore(
                                newnode, refnode.nextSibling)
                            newnode.parentNode.insertBefore(
                                xmlFile.createTextNode("\n"), newnode)

                    except WindowsError:  # pyflakes.ignore
                        foldersize = "N/A"
                        folder = "N/A"

                    newnode = xmlFile.createElement("FOLDERSIZE")
                    newtext = xmlFile.createTextNode(str(foldersize))
                    refnode = selectnode.getElementsByTagName("FOLDER")[0]

                    newnode.appendChild(newtext)
                    refnode.parentNode.insertBefore(newnode,
                                                    refnode.nextSibling)
                    newnode.parentNode.insertBefore(
                        xmlFile.createTextNode("\n"), newnode)

                    # Software Size estimated by Operating System
                    try:
                        estimatedSize = _winreg.QueryValueEx(
                            subkey, "EstimatedSize")[0]
                        if not (estimatedSize > 0):
                            estimatedSize = "N/A"
                    except WindowsError:  # pyflakes.ignore
                        estimatedSize = "N/A"

                    selectnode.getElementsByTagName(
                        "FILESIZE")[0].firstChild.nodeValue = estimatedSize

                    #Uninstall command
                    try:
                        uninstallCommand = _winreg.QueryValueEx(
                            subkey, "UninstallString")[0]
                    except WindowsError:  # pyflakes.ignore
                        uninstallCommand = "N/A"

                    if len(uninstallCommand) == 0:
                        uninstallCommand = "N/A"

                    newnode = xmlFile.createElement("UNINSTALL")
                    newtext = xmlFile.createTextNode(uninstallCommand)

                    newnode.appendChild(newtext)
                    selectnode.appendChild(newnode)
                    selectnode.appendChild(xmlFile.createTextNode("\n"))

                    # update detections
                    isUpdate = False
                    if updateDetection:
                        try:
                            parentKey = _winreg.QueryValueEx(
                                subkey, "ParentKeyName")[0]
                            isUpdate = True
                            nodeParentId = -1
                            if len(parentKey) > 0:
                                if parentKey == 'OperatingSystem':  #Update de l'OS
                                    nodeParentId = foundNodeInList(
                                        listSoftXMLDefault, "NAME", OSNAME)
                                    parentName = OSNAME
                                else:
                                    try:
                                        parentRegisterKey = _winreg.OpenKey(
                                            _winreg.HKEY_LOCAL_MACHINE,
                                            "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\\"
                                            + parentKey)
                                        parentName = _winreg.QueryValueEx(
                                            parentRegisterKey,
                                            "DisplayName")[0]
                                        _winreg.CloseKey(parentRegisterKey)
                                        nodeParentId = foundNodeInList(
                                            listSoftXMLDefault, "NAME",
                                            parentName)
                                    except WindowsError:  # if parent doesn't exist # pyflakes.ignore
                                        parentName = _winreg.QueryValueEx(
                                            subkey, "ParentDisplayName")[0]
                                        if len(
                                                parentName
                                        ) > 0:  # search parent with his name
                                            nodeParentId = foundNodeInList(
                                                listSoftXMLDefault, "NAME",
                                                parentName)
                                            if nodeParentId == -1:  # create the simulated parent
                                                newnode = defaultNode.cloneNode(
                                                    1)
                                                nodeslist = newnode.childNodes
                                                for j in range(
                                                        0, len(nodeslist)):
                                                    if j % 2 == 1:
                                                        nodeslist[
                                                            j].firstChild.nodeValue = "N/A"

                                                newnode.getElementsByTagName(
                                                    "NAME"
                                                )[0].firstChild.nodeValue = parentName
                                                xmlFile.getElementsByTagName(
                                                    "CONTENT")[0].insertBefore(
                                                        newnode,
                                                        listSoftXMLDefault[len(
                                                            listSoftXMLDefault)
                                                                           -
                                                                           1])
                                                nodeParentId = foundNodeInList(
                                                    listSoftXMLDefault, "NAME",
                                                    parentName)

                                            listSoftXMLDefault = xmlFile.getElementsByTagName(
                                                "SOFTWARES")
                                            nodeParentId = foundNodeInList(
                                                listSoftXMLDefault, "NAME",
                                                parentName)

                                if nodeParentId > -1:
                                    '''
                                    selectnode.tagName = "UPDATE"                       #to transformed the select node (update) 
                                    del(listSoftXML[nodeId])                            #on child of his parent node (software updated)
                                    selectnode.parentNode.removeChild(selectnode.previousSibling)
                                    listSoftXMLDefault[nodeParentId].appendChild(selectnode)
                                    listSoftXMLDefault[nodeParentId].appendChild(xmlFile.createTextNode("\n"))
                                    '''

                                    selectnode.setAttribute(
                                        "parent", parentName
                                    )  #only notified the dependance by attribute
                                    del (listSoftXML[nodeId])

                        except WindowsError:  # pyflakes.ignore
                            isUpdate = False

                    # if not update, we calculate this Rate Of Use and get icon
                    #log-on frequency    Only for WinXP et 2K (On Vista, it's doesn't exist)
                    if not updateDetection or (updateDetection
                                               and not isUpdate):
                        try:
                            arpKey = _winreg.OpenKey(
                                _winreg.HKEY_LOCAL_MACHINE,
                                "SOFTWARE\Microsoft\Windows\CurrentVersion\App Management\ARPCache\\"
                                + keyname)
                            try:
                                rateOfUse = _winreg.QueryValueEx(
                                    arpKey, "SlowInfoCache")[0]
                                valueRateOfUse = ord(rateOfUse[24])
                                if valueRateOfUse == 255:
                                    valueRateOfUse = "N/A"

                            except WindowsError:  # pyflakes.ignore
                                valueRateOfUse = "N/A"

                            _winreg.CloseKey(arpKey)
                        except WindowsError:  # pyflakes.ignore
                            valueRateOfUse = "N/A"

                        refnode = selectnode.getElementsByTagName("RATEOFUSE")
                        if len(refnode) == 0:
                            newnode = xmlFile.createElement("RATEOFUSE")
                            newtext = xmlFile.createTextNode(
                                str(valueRateOfUse))

                            newnode.appendChild(newtext)
                            selectnode.appendChild(newnode)
                            selectnode.appendChild(
                                xmlFile.createTextNode("\n"))
                        else:
                            if valueRateOfUse != "N/A":
                                if refnode[0].firstChild.valueNode != "N/A":
                                    refnode[0].firstChild.valueNode = refnode[
                                        0].firstChild.valueNode + valueRateOfUse
                                else:
                                    refnode[
                                        0].firstChild.valueNode = valueRateOfUse

                        if Pulse2InventoryProxyConfig().addicon:
                            try:
                                iconpath = _winreg.QueryValueEx(
                                    subkey, "DisplayIcon")[0]
                                if iconpath[0] == '"':
                                    iconpath = iconpath[1:len(iconpath) - 1]

                                k = len(iconpath) - 1
                                while (k > (len(iconpath) - 4)
                                       and iconpath[k] != ','):
                                    k -= 1

                                nIcon = 0
                                if iconpath[k] == ',':
                                    try:
                                        if (k < len(iconpath)):
                                            nIcon = int(iconpath[k + 1])
                                    except ValueError:
                                        pass
                                    iconpath = iconpath[0:k]
                                length = len(iconpath)

                                if iconpath[length - 3:] == 'ico':
                                    stringBit = windowsIconGetter(
                                        iconpath, nIcon, False)
                                else:
                                    stringBit = windowsIconGetter(
                                        iconpath, nIcon, True)

                                if stringBit != None:
                                    newnode = xmlFile.createElement("ICON")
                                    newtext = xmlFile.createTextNode(stringBit)

                                    newnode.appendChild(newtext)
                                    selectnode.appendChild(newnode)
                                    selectnode.appendChild(
                                        xmlFile.createTextNode("\n"))

                            except WindowsError:  # pyflakes.ignore
                                pass

            except WindowsError:  # pyflakes.ignore
                pass

            _winreg.CloseKey(subkey)
            i += 1

    except WindowsError:  # pyflakes.ignore
        pass

    if Pulse2InventoryProxyConfig().addicon:
        # Do NOT FORGET !
        os.remove(dirTmpFile)

    _winreg.CloseKey(key)
    xmlString = xmlFile.toxml("utf-8")
    return xmlString
示例#6
0
# along with Pulse 2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
'''
This is the module to add information to OCS XML
for the Windows platforms
'''

import wmi
import _winreg
import os
import xml.dom.minidom

from pulse2.proxyssl.config import Pulse2InventoryProxyConfig

if Pulse2InventoryProxyConfig().addicon:
    import win32ui
    import win32gui
    import win32con
    import win32api
    import cStringIO
    import Image  # need install PIL package http://www.pythonware.com/products/pil/
    import base64
    import tempfile

    #system icon size
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)

    #tempory file
    tmpfile = tempfile.mkstemp()
    dirTmpFile = tmpfile[1]
class MyProxyRequest(proxy.ProxyRequest):

    """
    Proxy that handle a outgoing HTTP or HTTPS connection.
    For HTTPS. create a SSL context according to the configuration file.
    """

    config = Pulse2InventoryProxyConfig()
    ports = {'http' : config.port, 'https' : config.port }
    protocols = {'http': MyProxyClientFactory, 'https': MyProxyClientFactory}

    def process(self):
        self.uri = "%s:%d%s" % (self.config.server, self.config.port, self.uri)
        if self.config.enablessl:
            self.uri = "https://" + self.uri
        else:
            self.uri = "http://" + self.uri
        parsed = urlparse.urlparse(self.uri)
        protocol = parsed[0]
        host = parsed[1]
        port = self.ports[protocol]
        if ':' in host:
            host, port = host.split(':')
            port = int(port)
        rest = urlparse.urlunparse(('', '') + parsed[2:])
        if not rest:
            rest = rest + '/'
        class_ = self.protocols[protocol]
        headers = self.getAllHeaders().copy()
        if 'host' not in headers:
            headers['host'] = host
        self.content.seek(0, 0)
        s = self.content.read()

        logger = logging.getLogger()

        logger.debug("\nOcs Report Received");

        # We will unzip the XML File and parsing it only if needed
        if self.config.getocsdebuglog or self.config.improve:
            # xml file unzip
            try:
                decomp = decompressobj()
                sUnpack = decomp.decompress(s)
                if decomp.unused_data:
                    logger.warn("The zip content seems to be bad.")
                    logger.debug("The remaining bytes are : %s"%(decomp.unused_data))
            except Exception, e:
                logger.error("Failed during decompression.")
                logger.error(str(e))
                raise e

            # Get the query type
            try:
                query = re.search(r'<QUERY>([\w-]+)</QUERY>', sUnpack).group(1)
            except AttributeError, e:
                query = 'FAILS'

            # process on Inventory OCS XML file,
            if query == 'INVENTORY' :
                try:
                    if sys.platform[0:3] == "win":                          #It's here because I need Pulse2InventoryProxyConfig be initialited before improve packtage be initialat
                        from improveWin import improveXML,getOcsDebugLog
                    elif sys.platform == "mac":
                        from improveMac import improveXML,getOcsDebugLog # pyflakes.ignore
                    else:
                        from improveUnix import improveXML,getOcsDebugLog # pyflakes.ignore
                    logger.debug("\tOcs Inventory Report Processing")
                    if self.config.getocsdebuglog:
                        # Add Ocs Log File
                        sUnpack = getOcsDebugLog(sUnpack)
                        logger.debug("\t\tOcs Debug Log add")
                    if self.config.improve:
                        # improving of xml file
                        sUnpack = improveXML(sUnpack)
                        logger.debug("\t\tInformations add")
                except ImportError:
                    logger.error("OCS improving failed: no improving function found for "+sys.platform+" platform")

            logger.debug("\tOcs Report Terminated");
            logger.debug("\t\tuncompressed length: " + str(len(sUnpack)))

            # zip of xml file
            try:
                comp = compressobj()
                s = comp.compress(sUnpack) + comp.flush() # default to Z_FINISH
                logger.debug("\t\tcompressed length: " + str(len(s)))
            except Exception, e:
                logger.error("Failed during compression.")
                logger.error(str(e))
                raise e