コード例 #1
0
def DisplayObjectAssociators(grph, wmiInstanceNode, objWmi, cgiMoniker):
    sys.stderr.write("DisplayObjectAssociators\n")
    # It is possible to restrict the associators to a specific class only.
    for anAssoc in objWmi.associators():
        # assocMoniker=\\RCHATEAU-HP\root\cimv2:Win32_ComputerSystem.Name="RCHATEAU-HP"
        assocMoniker = str(anAssoc.path())
        sys.stderr.write("DisplayObjectAssociators anAssoc Moniker=%s\n" %
                         assocMoniker)

        # derivation=(u'CIM_UnitaryComputerSystem', u'CIM_ComputerSystem', u'CIM_System', u'CIM_LogicalElement', u'CIM_ManagedSystemElement')
        assocDerivation = anAssoc.derivation()

        sys.stderr.write("DisplayObjectAssociators anAssoc derivation=%s\n" %
                         str(assocDerivation))
        # sys.stderr.write("DisplayObjectAssociators anAssoc=%s\n"%str(dir(anAssoc)))

        # TODO: Consider these methods: associated_classes, associators, derivation,
        # id, keys, methods, ole_object, path, properties, property_map, put,
        # qualifiers, references, set, wmi_property

        # BEWARE: For example for CIM_ComputerSystem, the host name must be in lowercase.
        # TODO: This is not done here. Luckily the universal alias does this properly.
        assocInstanceUrl = lib_util.EntityUrlFromMoniker(assocMoniker)
        assocInstanceNode = lib_common.NodeUrl(assocInstanceUrl)
        grph.add((wmiInstanceNode, lib_common.MakeProp(assocDerivation[0]),
                  assocInstanceNode))
コード例 #2
0
ファイル: entity_wmi.py プロジェクト: rchateauneu/survol
def DisplayObjectAssociators(grph, wmi_instance_node, obj_wmi, cgiMoniker):
    logging.debug("DisplayObjectAssociators.")
    # It is possible to restrict the associators to a specific class only.
    for an_assoc in obj_wmi.associators():
        # assoc_moniker=\\MYMACHINE\root\cimv2:Win32_ComputerSystem.Name="MYMACHINE"
        assoc_moniker = str(an_assoc.path())
        logging.debug("DisplayObjectAssociators an_assoc Moniker=%s",
                      assoc_moniker)

        # derivation=(u'CIM_UnitaryComputerSystem', u'CIM_ComputerSystem', u'CIM_System',
        # u'CIM_LogicalElement', u'CIM_ManagedSystemElement')
        assoc_derivation = an_assoc.derivation()

        logging.debug("DisplayObjectAssociators an_assoc derivation=%s",
                      str(assoc_derivation))

        # TODO: Consider these methods: associated_classes, associators, derivation,
        # id, keys, methods, ole_object, path, properties, property_map, put,
        # qualifiers, references, set, wmi_property

        # BEWARE: For example for CIM_ComputerSystem, the host name must be in lowercase.
        # TODO: This is not done here. Luckily the universal alias does this properly.
        assoc_instance_url = lib_util.EntityUrlFromMoniker(assoc_moniker)
        assoc_instance_node = lib_common.NodeUrl(assoc_instance_url)
        grph.add((wmi_instance_node, lib_common.MakeProp(assoc_derivation[0]),
                  assoc_instance_node))
コード例 #3
0
def WbemInstanceUrl(entity_namespace, entity_type, entity_id, cimom_srv):
    wbem_full_path = WbemBuildMonikerPath(entity_namespace, entity_type,
                                          entity_id)

    if wbem_full_path is None:
        return None

    # 'https://*****:*****@acme.com:5959/cimv2:Win32_SoftwareFeature.Name="Havana",ProductName="Havana",Version="1.0"'
    wbem_moniker = cimom_srv + "/" + wbem_full_path

    wbem_instance_url = lib_util.EntityUrlFromMoniker(wbem_moniker,
                                                      entity_id == "")
    return wbem_instance_url
コード例 #4
0
def WbemInstanceUrl(entity_namespace, entity_type, entity_id, cimomSrv):
    # sys.stderr.write("WbemInstanceUrl %s %s %s %s\n" % (entity_namespace, entity_type, entity_id, cimomSrv))

    wbemFullPath = WbemBuildMonikerPath(entity_namespace, entity_type,
                                        entity_id)

    if wbemFullPath is None:
        return None

    # 'https://*****:*****@acme.com:5959/cimv2:Win32_SoftwareFeature.Name="Havana",ProductName="Havana",Version="1.0"'
    wbemMoniker = cimomSrv + "/" + wbemFullPath

    wbemInstanceUrl = lib_util.EntityUrlFromMoniker(wbemMoniker,
                                                    entity_id == "")
    return wbemInstanceUrl
コード例 #5
0
def WmiInstanceUrl(entity_namespace, entity_type, entity_id, entity_host):
    # sys.stderr.write("WmiInstanceUrl %s %s %s %s\n" % (entity_namespace, entity_type, entity_id, entity_host))

    wmiFullPath = WmiBuildMonikerPath(entity_namespace, entity_type, entity_id)

    if wmiFullPath is None:
        return None

    # sys.stderr.write("WmiInstanceUrl wmiFullPath=%s\n" % (wmiFullPath))

    # 'https://*****:*****@acme.com:5959/cimv2:Win32_SoftwareFeature.Name="Havana",ProductName="Havana",Version="1.0"'
    wmiMoniker = "\\\\" + entity_host + "\\" + wmiFullPath
    wmiInstanceUrl = lib_util.EntityUrlFromMoniker(wmiMoniker, entity_id == "")

    # sys.stderr.write("WmiInstanceUrl wmiInstanceUrl=%s\n" % (wmiInstanceUrl))
    return wmiInstanceUrl
コード例 #6
0
ファイル: entity_wmi.py プロジェクト: rchateauneu/survol
def DispWmiReferences(grph, wmi_instance_node, obj_wmi, cgi_moniker):
    for obj_ref in obj_wmi.references():
        literal_key_value = dict()
        ref_instance_node = None
        for key_prp in obj_ref.properties:
            val_prp = getattr(obj_ref, key_prp)
            try:
                # references() have one leg pointing to the current object,
                ref_moniker = str(val_prp.path())

                # Maybe it would be better to compare the objects ???
                if not EqualMonikers(ref_moniker, cgi_moniker):
                    # TODO: Disabled for the moment because we do not understand the logic.
                    if False and ref_instance_node is not None:
                        # Inconsistency:\\MYMACHINE\root\cimv2:Win32_LogonSession.LogonId="195361"
                        # != \\192.168.1.83\root\CIMV2:CIM_Process.Handle=7120
                        lib_common.ErrorMessageHtml("Inconsistency:" +
                                                    ref_moniker + " != " +
                                                    cgi_moniker)
                    ref_instance_url = lib_util.EntityUrlFromMoniker(
                        ref_moniker)
                    ref_instance_node = lib_common.NodeUrl(ref_instance_url)
                    grph.add((wmi_instance_node, lib_common.MakeProp(key_prp),
                              ref_instance_node))
            except AttributeError:
                # Then it is a literal attribute.
                # TODO: Maybe we could test if the type is an instance.
                # Beware: UnicodeEncodeError: 'ascii' codec can't encode character u'\\u2013'
                try:
                    literal_key_value[key_prp] = str(val_prp)
                except UnicodeEncodeError:
                    literal_key_value[key_prp] = "UnicodeEncodeError"

        # Now the literal properties are attached to the other node.
        if ref_instance_node != None:
            for key_litt in literal_key_value:
                grph.add((ref_instance_node, lib_common.MakeProp(key_litt),
                          lib_util.NodeLiteral(literal_key_value[key_litt])))
コード例 #7
0
def ClassUrl(nskey, cimom_url, class_nam):
    wbem_moniker = BuildWbemMoniker(cimom_url, nskey, class_nam)
    wbem_instance_url = lib_util.EntityUrlFromMoniker(wbem_moniker, True)
    return wbem_instance_url
コード例 #8
0
ファイル: entity_wmi.py プロジェクト: rchateauneu/survol
def Main():
    paramkey_display_none = "Display none values"
    paramkey_display_associators = "Display Associators"
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True,
                                          parameters={
                                              paramkey_display_none: False,
                                              paramkey_display_associators:
                                              False
                                          })

    display_none_values = bool(cgiEnv.get_parameters(paramkey_display_none))
    display_associators = bool(
        cgiEnv.get_parameters(paramkey_display_associators))

    name_space, class_name = cgiEnv.get_namespace_type()
    # If name_space is not provided, it is set to "root/CIMV2" by default.
    if not class_name:
        lib_common.ErrorMessageHtml("Class name should not be empty")

    wmi_host = cgiEnv.GetHost()

    # wmi_host=MYMACHINE ns=root\cimv2 cls=Win32_ComputerSystem id=Name="MYMACHINE"
    logging.debug("wmi_host=%s ns=%s cls=%s id=%s", wmi_host, name_space,
                  class_name, cgiEnv.m_entity_id)

    grph = cgiEnv.GetGraph()

    try:
        conn_wmi = lib_wmi.WmiConnect(wmi_host, name_space)
    except Exception as exc:
        lib_common.ErrorMessageHtml(
            "entity_wmi.py: Cannot connect to WMI server %s with namespace %s: %s"
            % (wmi_host, name_space, str(exc)))

    # Try to read the moniker, which is much faster, but it does not always work if we do not have all the properties.
    cgi_moniker = cgiEnv.get_parameters("xid")
    logging.debug("cgi_moniker=[%s]", cgi_moniker)

    obj_list = WmiReadWithMoniker(cgiEnv, cgi_moniker)
    if obj_list is None:
        # If no object associated with the moniker, then tries a WQL query which might return several objects.
        # BEWARE: This is slow and less efficient than using WMI filters.
        obj_list = WmiReadWithQuery(cgiEnv, conn_wmi, class_name)

    wmi_instance_url = lib_util.EntityUrlFromMoniker(cgi_moniker)

    # Possible problem because this associates a single URL with possibly several objects ??
    wmi_instance_node = lib_common.NodeUrl(wmi_instance_url)

    # In principle, there should be only one object to display.
    # TODO: If several instances, the instance node must be recreated.
    for obj_wmi in obj_list:
        logging.debug("entity_wmi.py obj_wmi=[%s]", str(obj_wmi))

        DispWmiProperties(grph, conn_wmi, wmi_instance_node, obj_wmi,
                          display_none_values, class_name)

        # Displaying these classes is very slow, several minutes for 100 elements.
        # It would be better to have another link.
        if not lib_wmi.WmiTooManyInstances(class_name):
            try:
                DispWmiReferences(grph, wmi_instance_node, obj_wmi,
                                  cgi_moniker)
            except Exception as exc:
                logging.warning("Exception=%s", str(exc))
        else:
            # Prefix with a dot so it is displayed first.
            grph.add((wmi_instance_node, lib_common.MakeProp(".REFERENCES"),
                      lib_util.NodeLiteral("DISABLED")))

        # Displaying the associators is conditional because it slows things.
        # TODO: How to select this option with D3 ?????
        if display_associators:
            # This class appears everywhere, so not not display its references, it would be too long.
            if class_name == "Win32_ComputerSystem":
                grph.add(
                    (wmi_instance_node, lib_common.MakeProp(".ASSOCIATORS"),
                     lib_util.NodeLiteral("DISABLED")))
            else:
                DisplayObjectAssociators(grph, wmi_instance_node, obj_wmi,
                                         cgi_moniker)

    # Adds the class node to the instance.
    wmi_class_node = lib_wmi.WmiAddClassNode(grph, conn_wmi, wmi_instance_node,
                                             wmi_host, name_space, class_name,
                                             lib_common.MakeProp(class_name))

    # Now displays the base class, up to the top.
    lib_wmi.WmiAddBaseClasses(grph, conn_wmi, wmi_class_node, wmi_host,
                              name_space, class_name)

    # Now tries to find the equivalent object in the Survol terminology.
    AddSurvolObjectFromWmi(grph, wmi_instance_node, conn_wmi, class_name,
                           obj_list)

    # BEWARE: Mustbe done for all classes
    cgiEnv.OutCgiRdf("LAYOUT_TWOPI", [
        lib_common.MakeProp('PartComponent'),
        lib_common.MakeProp('Element'),
        lib_common.MakeProp('Antecedent')
    ])
コード例 #9
0
def Main():
    paramkeyEnumInstances = "Enumerate instances"

    cgiEnv = lib_common.CgiEnv(parameters={paramkeyEnumInstances: False})

    flagEnumInstances = bool(cgiEnv.get_parameters(paramkeyEnumInstances))

    grph = cgiEnv.GetGraph()

    nameSpace, className = cgiEnv.get_namespace_type()
    INFO("nameSpace=%s className=%s", nameSpace, className)

    # If nameSpace is not provided, it is set to "root/CIMV2" by default.
    if not className:
        lib_common.ErrorMessageHtml("Class name should not be empty")

    cimomUrl = cgiEnv.GetHost()

    rootNode = lib_util.EntityClassNode(className, nameSpace, cimomUrl, "WMI")

    AddExtraNodes(grph, rootNode)

    # Not sure why, but sometimes backslash replaced by slash, depending where we come from ?
    nameSpace = nameSpace.replace("/", "\\")

    try:
        connWmi = lib_wmi.WmiConnect(cimomUrl, nameSpace)
    except:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml(
            "WMI Connecting to cimomUrl=%s nameSpace=%s Caught:%s\n" %
            (cimomUrl, nameSpace, str(exc)))

    # http://rchateau-hp:8000/survol/class_wmi.py?xid=\\rchateau-HP\root\CIMV2%3ACIM_Directory.
    # http://rchateau-hp:8000/survol/class_wmi.py?xid=\rchateau-HP\root\CIMV2%3ACIM_Directory.&mode=html

    lib_wmi.WmiAddClassQualifiers(grph, connWmi, rootNode, className, True)

    # Inutilisable pour:
    # root/CIMV2/CIM_LogicalFile
    # car il y en a beaucoup trop.
    # TODO: pEUT-ETRE QUE wql POURRAQIT PERMETTRE UNE LIMITE ??
    # Ou bien arguments: De 1 a 100 etc... mais ca peut nous obliger de creer des liens bidons
    # pour aller aux elements suivants ou precedents. Notons que ca revient a creer des scripts artificiels.

    # Et aussi, revenir vers l'arborescence des classes dans ce namespace.

    try:
        wmiClass = getattr(connWmi, className)
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml(
            "class_wmi.py cimomUrl=%s nameSpace=%s className=%s Caught:%s\n" %
            (cimomUrl, nameSpace, className, str(exc)))

    # wmiClass=[Abstract, Locale(1033): ToInstance, UUID("{8502C55F-5FBB-11D2-AAC1-006008C78BC7}"): ToInstance]
    # class CIM_Directory : CIM_LogicalFile
    # {
    # };
    DEBUG("wmiClass=%s", str(wmiClass))

    # Some examples of WMI queries.
    # http://timgolden.me.uk/python/wmi/tutorial.html
    #
    # logical_disk = wmi.WMI(moniker="//./root/cimv2:Win32_LogicalDisk")
    # c_drive = wmi.WMI(moniker='//./root/cimv2:Win32_LogicalDisk.DeviceID="C:"')
    # c = wmi.WMI("MachineB", user=r"MachineB\fred", password="******")
    #
    # A WMI class can be "called" with simple equal-to parameters to narrow down the list.
    # This filtering is happening at the WMI level.
    # for disk in c.Win32_LogicalDisk(DriveType=3):
    # for service in c.Win32_Service(Name="seclogon"):
    #
    # Arbitrary WQL queries can be run, but apparently WQL selects first all elements from WMI,
    # then only does its filtering:
    # for disk in wmi.WMI().query("SELECT Caption, Description FROM Win32_LogicalDisk WHERE DriveType <> 3"):
    #
    if flagEnumInstances:

        # Biggest difficulty is the impossibility to limit the numbers of results fetched by WMI.
        # Many classes have to many elements to display them.
        # This makes it virtually impossible to select their elements.
        if lib_wmi.WmiTooManyInstances(className):
            lib_common.ErrorMessageHtml("Too many elements in className=%s\n" %
                                        (className))

        try:
            lstObj = wmiClass()
        except Exception:
            exc = sys.exc_info()[1]
            lib_common.ErrorMessageHtml("Caught when getting list of %s\n" %
                                        className)

        numLstObj = len(lstObj)
        DEBUG("className=%s type(wmiClass)=%s len=%d", className,
              str(type(wmiClass)), numLstObj)

        if numLstObj == 0:
            grph.add((rootNode, pc.property_information,
                      lib_common.NodeLiteral("No instances in this class")))

        for wmiObj in lstObj:
            # Full natural path: We must try to merge it with WBEM Uris.
            # '\\\\RCHATEAU-HP\\root\\cimv2:Win32_Process.Handle="0"'
            # https://jdd:[email protected]:5959/cimv2:Win32_SoftwareFeature.Name="Havana",ProductName="Havana",Version="1.0"

            try:
                fullPth = str(wmiObj.path())
            except UnicodeEncodeError:
                # UnicodeEncodeError: 'ascii' codec can't encode characters in position 104-108: ordinal not in range(128)
                exc = sys.exc_info()[1]
                WARNING("Exception %s", str(exc))
                continue

            # sys.stderr.write("fullPth=%s\n" % fullPth)

            if fullPth == "":
                WARNING("Empty path wmiObj=%s", str(wmiObj))
                # The class Win32_PnPSignedDriver (Maybe others) generates dozens of these messages.
                # This is not really an issue as this class should be hidden from applications.
                # WARNING Empty path wmiObj=
                # instance of Win32_PnPSignedDriver
                # {
                # 		ClassGuid = NULL;
                # 		CompatID = NULL;
                # 		Description = NULL;
                # 		DeviceClass = "LEGACYDRIVER";
                # 		DeviceID = "ROOT\\LEGACY_LSI_FC\\0000";
                # 		DeviceName = "LSI_FC";
                # 		DevLoader = NULL;
                # 		DriverName = NULL;
                # 		DriverProviderName = NULL;
                # 		DriverVersion = NULL;
                # 		FriendlyName = NULL;
                # 		HardWareID = NULL;
                # 		InfName = NULL;
                # 		Location = NULL;
                # 		Manufacturer = NULL;
                # 		PDO = NULL;
                # };
                continue

            # fullPth=\\RCHATEAU-HP\root\CIMV2:Win32_SoundDevice.DeviceID="HDAUDIO\\FUNC_01&VEN_10EC&DEV_0221&SUBSYS_103C18E9&REV_1000\\4&3BC582&0&0001"
            fullPth = fullPth.replace("&", "&amp;")
            wmiInstanceUrl = lib_util.EntityUrlFromMoniker(fullPth)
            DEBUG("wmiInstanceUrl=%s", wmiInstanceUrl)

            wmiInstanceNode = lib_common.NodeUrl(wmiInstanceUrl)

            # infos = lib_wbem_cim.get_inst_info(iname, klass, include_all=True, keys_only=True)

            grph.add((rootNode, pc.property_class_instance, wmiInstanceNode))

    # TODO: On pourrait rassembler par classes, et aussi afficher les liens d'heritages des classes.

    cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_class_instance])
コード例 #10
0
ファイル: class_wmi.py プロジェクト: rchateauneu/survol
def Main():
    paramkey_enum_instances = "Enumerate instances"

    cgiEnv = lib_common.ScriptEnvironment(
        parameters={paramkey_enum_instances: False})

    flag_enum_instances = bool(cgiEnv.get_parameters(paramkey_enum_instances))

    grph = cgiEnv.GetGraph()

    name_space, class_name = cgiEnv.get_namespace_type()
    logging.info("name_space=%s class_name=%s", name_space, class_name)

    # If name_space is not provided, it is set to "root/CIMV2" by default.
    if not class_name:
        lib_common.ErrorMessageHtml("Class name should not be empty")

    cimom_url = cgiEnv.GetHost()

    root_node = lib_util.EntityClassNode(class_name, name_space, cimom_url,
                                         "WMI")

    _add_extra_nodes(grph, root_node)

    # Not sure why, but sometimes backslash replaced by slash, depending where we come from ?
    name_space = name_space.replace("/", "\\")

    try:
        conn_wmi = lib_wmi.WmiConnect(cimom_url, name_space)
    except Exception as exc:
        lib_common.ErrorMessageHtml(
            "WMI Connecting to cimom_url=%s name_space=%s Caught:%s\n" %
            (cimom_url, name_space, str(exc)))

    # http://mymachine:8000/survol/class_wmi.py?xid=\\mymachine\root\CIMV2%3ACIM_Directory.
    # http://mymachine:8000/survol/class_wmi.py?xid=\mymachine\root\CIMV2%3ACIM_Directory.&mode=html

    lib_wmi.WmiAddClassQualifiers(grph, conn_wmi, root_node, class_name, True)

    try:
        wmi_class = getattr(conn_wmi, class_name)
    except Exception as exc:
        lib_common.ErrorMessageHtml(
            "class_wmi.py cimom_url=%s name_space=%s class_name=%s Caught:%s\n"
            % (cimom_url, name_space, class_name, str(exc)))

    # wmi_class=[Abstract, Locale(1033): ToInstance, UUID("{8502C55F-5FBB-11D2-AAC1-006008C78BC7}"): ToInstance]
    # class CIM_Directory : CIM_LogicalFile
    # {
    # };
    logging.debug("wmi_class=%s", str(wmi_class))

    # Some examples of WMI queries.
    # http://timgolden.me.uk/python/wmi/tutorial.html
    #
    # logical_disk = wmi.WMI(moniker="//./root/cimv2:Win32_LogicalDisk")
    # c_drive = wmi.WMI(moniker='//./root/cimv2:Win32_LogicalDisk.DeviceID="C:"')
    # c = wmi.WMI("MachineB", user=r"MachineB\fred", password="******")
    #
    # A WMI class can be "called" with simple equal-to parameters to narrow down the list.
    # This filtering is happening at the WMI level.
    # for disk in c.Win32_LogicalDisk(DriveType=3):
    # for service in c.Win32_Service(Name="seclogon"):
    #
    # Arbitrary WQL queries can be run, but apparently WQL selects first all elements from WMI,
    # then only does its filtering:
    # for disk in wmi.WMI().query("SELECT Caption, Description FROM Win32_LogicalDisk WHERE DriveType <> 3"):
    #
    if flag_enum_instances:
        # Biggest difficulty is the impossibility to limit the numbers of results fetched by WMI.
        # Many classes have to many elements to display them.
        # This makes it virtually impossible to select their elements.
        if lib_wmi.WmiTooManyInstances(class_name):
            lib_common.ErrorMessageHtml(
                "Too many elements in class_name=%s\n" % class_name)

        try:
            lst_obj = wmi_class()
        except Exception as exc:
            lib_common.ErrorMessageHtml("Caught when getting list of %s\n" %
                                        class_name)

        num_lst_obj = len(lst_obj)
        logging.debug("class_name=%s type(wmi_class)=%s len=%d", class_name,
                      str(type(wmi_class)), num_lst_obj)

        if num_lst_obj == 0:
            grph.add((root_node, pc.property_information,
                      lib_util.NodeLiteral("No instances in this class")))

        for wmi_obj in lst_obj:
            # Full natural path: We must try to merge it with WBEM Uris.
            # '\\\\MYMACHINE\\root\\cimv2:Win32_Process.Handle="0"'
            # https://jdd:[email protected]:5959/cimv2:Win32_SoftwareFeature.Name="Havana",ProductName="Havana",Version="1.0"

            try:
                full_pth = str(wmi_obj.path())
            except UnicodeEncodeError as exc:
                # UnicodeEncodeError: 'ascii' codec can't encode characters in position 104-108: ordinal not in range(128)
                logging.warning("Exception %s", str(exc))
                continue

            if full_pth == "":
                logging.warning("Empty path wmi_obj=%s", str(wmi_obj))
                # The class Win32_PnPSignedDriver (Maybe others) generates dozens of these messages.
                # This is not really an issue as this class should be hidden from applications.
                # logging.warning Empty path wmi_obj=
                # instance of Win32_PnPSignedDriver
                # {
                #         ClassGuid = NULL;
                #         CompatID = NULL;
                #         Description = NULL;
                #         DeviceClass = "LEGACYDRIVER";
                #         DeviceID = "ROOT\\LEGACY_LSI_FC\\0000";
                #         DeviceName = "LSI_FC";
                #         DevLoader = NULL;
                #         DriverName = NULL;
                #         DriverProviderName = NULL;
                #         DriverVersion = NULL;
                #         FriendlyName = NULL;
                #         HardWareID = NULL;
                #         InfName = NULL;
                #         Location = NULL;
                #         Manufacturer = NULL;
                #         PDO = NULL;
                # };
                continue

            # full_pth=\\MYMACHINE\root\CIMV2:Win32_SoundDevice.DeviceID="HDAUDIO\\FUNC_01&VEN_10EC&DEV_0221&SUBSYS_103C18E9&REV_1000\\4&3BC582&0&0001"
            full_pth = full_pth.replace("&", "&amp;")
            wmi_instance_url = lib_util.EntityUrlFromMoniker(full_pth)
            logging.debug("wmi_instance_url=%s", wmi_instance_url)

            wmi_instance_node = lib_common.NodeUrl(wmi_instance_url)

            grph.add(
                (root_node, pc.property_class_instance, wmi_instance_node))

    # TODO: On pourrait rassembler par classes, et aussi afficher les liens d'heritages des classes.

    cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_class_instance])
コード例 #11
0
def DispWmiProperties(grph, wmiInstanceNode, objWmi, displayNoneValues,
                      className, mapPropUnits):
    """
		Displays the properties of a WMI object (Not a class),
		then sticks them to the WMI object node.
	"""

    for prpName in objWmi.properties:

        # Some common properties are not displayed because the value is cumbersome
        # and the occurrence repetitive.
        if prpName in ["OSName"]:
            continue

        prpProp = lib_common.MakeProp(prpName)

        try:
            valUnit = mapPropUnits[prpName]
        except KeyError:
            valUnit = ""

        # CIM_ComputerSystem
        try:
            doNotDisplay = prpName in prpCannotBeDisplayed[className]
        except KeyError:
            doNotDisplay = False

        if doNotDisplay:
            sys.stderr.write("Cannot display:%s\n" %
                             str(getattr(objWmi, prpName)))
            value = "Cannot be displayed"
        else:
            # BEWARE, it could be None.
            value = getattr(objWmi, prpName)

        # Date format: "20189987698769876.97987+000", Universal Time Coordinate (UTC)
        # yyyymmddHHMMSS.xxxxxx +- UUU
        # yyyy represents the year.
        # mm represents the month.
        # dd represents the day.
        # HH represents the hour (in 24-hour format).
        # MM represents the minutes.
        # SS represents the seconds.
        # xxxxxx represents the milliseconds.
        # UUU represents the difference, in minutes, between the local time zone and Greenwich Mean Time (GMT).
        if prpName in ["CreationDate"]:
            try:
                dtYear = value[0:4]
                dtMonth = value[4:6]
                dtDay = value[6:8]
                dtHour = value[8:10]
                dtMinute = value[10:12]
                dtSecond = value[12:14]

                value = "%s-%s-%s %s:%s:%s" % (dtYear, dtMonth, dtDay, dtHour,
                                               dtMinute, dtSecond)
            except:
                pass

        # Some specific properties match a Survol class,
        # so it is possible to add a specific node.
        # THIS WORKS BUT IT IS NOT NICE, AS A SEPARATE NODE.
        # We would like to have a clickable URL displayed in a table TD.
        if prpName == "GUID":
            # Example: "{CF185B35-1F88-46CF-A6CE-BDECFBB59B4F}"
            nodeGUID = lib_common.gUriGen.ComTypeLibUri(value)
            grph.add((wmiInstanceNode, prpProp, nodeGUID))
            continue

        if isinstance(value, scalarDataTypes):
            # Special backslash replacement otherwise:
            # "NT AUTHORITY\\\\NetworkService" displayed as "NT AUTHORITYnd_0etworkService"
            # TODO: Why not CGI escaping ?
            valueReplaced = str(value).replace('\\', '\\\\')

            if valUnit:
                valueReplaced = UnitConversion(valueReplaced, valUnit)
            grph.add((wmiInstanceNode, prpProp,
                      lib_common.NodeLiteral(valueReplaced)))
        elif isinstance(value, (tuple)):
            # Special backslash replacement otherwise:
            # "NT AUTHORITY\\\\NetworkService" displayed as "NT AUTHORITYnd_0etworkService"
            # TODO: Why not CGI escaping ?
            tupleReplaced = [
                str(oneVal).replace('\\', '\\\\') for oneVal in value
            ]

            # tuples are displayed as tokens separated by ";". Examples:
            #
            # CIM_ComputerSystem.OEMStringArray
            #" ABS 70/71 60 61 62 63; ;FBYTE#2U3E3X47676J6S6b727H7M7Q7T7W7m8D949RaBagapaqb3bmced3.fH;; BUILDID#13WWHCHW602#SABU#DABU;"
            #
            # CIM_ComputerSystem.Roles
            # "LM_Workstation ; LM_Server ; SQLServer ; NT ; Potential_Browser ; Master_Browser"
            cleanTuple = " ; ".join(tupleReplaced)
            grph.add(
                (wmiInstanceNode, prpProp, lib_common.NodeLiteral(cleanTuple)))
        elif value is None:
            if displayNoneValues:
                grph.add(
                    (wmiInstanceNode, prpProp, lib_common.NodeLiteral("None")))
        else:
            try:
                refMoniker = str(value.path())
                refInstanceUrl = lib_util.EntityUrlFromMoniker(refMoniker)
                refInstanceNode = lib_common.NodeUrl(refInstanceUrl)
                grph.add((wmiInstanceNode, prpProp, refInstanceNode))
            except AttributeError:
                exc = sys.exc_info()[1]
                grph.add((wmiInstanceNode, prpProp,
                          lib_common.NodeLiteral(str(exc))))
コード例 #12
0
def Main():
    paramkeyDisplayNone = "Display none values"
    paramkeyDisplayAssociators = "Display Associators"
    cgiEnv = lib_common.CgiEnv(can_process_remote=True,
                               parameters={
                                   paramkeyDisplayNone: False,
                                   paramkeyDisplayAssociators: False
                               })

    displayNoneValues = bool(cgiEnv.GetParameters(paramkeyDisplayNone))
    displayAssociators = bool(cgiEnv.GetParameters(paramkeyDisplayAssociators))

    (nameSpace, className, entity_namespace_type) = cgiEnv.GetNamespaceType()

    wmiHost = cgiEnv.GetHost()

    # wmiHost=RCHATEAU-HP ns=root\cimv2 cls=Win32_ComputerSystem id=Name="RCHATEAU-HP"
    sys.stderr.write("entity_wmi.py wmiHost=%s ns=%s cls=%s id=%s\n" %
                     (wmiHost, nameSpace, className, cgiEnv.m_entity_id))

    grph = cgiEnv.GetGraph()

    try:
        connWmi = lib_wmi.WmiConnect(wmiHost, nameSpace)
    except:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml(
            "entity_wmi.py: Cannot connect to WMI server %s with namespace %s: %s"
            % (wmiHost, nameSpace, str(exc)))

    # Try to read the moniker, which is much faster,
    # but it does not always work if we do not have all the properties.
    cgiMoniker = cgiEnv.GetParameters("xid")
    sys.stderr.write("entity_wmi.py cgiMoniker=[%s]\n" % cgiMoniker)

    objList = WmiReadWithMoniker(cgiEnv, cgiMoniker)
    if objList is None:
        # If no object associated with the moniker, then tries a WQL query which might return several objects.
        # BEWARE: This is slow and less efficient than using WMI filters.
        objList = WmiReadWithQuery(cgiEnv, connWmi, className)

    wmiInstanceUrl = lib_util.EntityUrlFromMoniker(cgiMoniker)

    # Possible problem because this associates a single URL with possibly several objects ??
    wmiInstanceNode = lib_common.NodeUrl(wmiInstanceUrl)

    # This returns the map of units for all properties of a class.
    # Consider using the value of the property "OSCreationClassName",
    # because units properties of base classes are not always documented.
    mapPropUnits = lib_wmi.WmiDictPropertiesUnit(connWmi, className)

    # In principle, there should be only one object to display.
    for objWmi in objList:
        sys.stderr.write("entity_wmi.py objWmi=[%s]\n" % str(objWmi))

        DispWmiProperties(grph, wmiInstanceNode, objWmi, displayNoneValues,
                          className, mapPropUnits)

        # Displaying these classes is very slow, several minutes for 100 elements.
        # It would be better to have another link.
        # rchref = wmi.WMI().query("select * from Win32_UserAccount where Name='rchateau'")[0].references()
        if not lib_wmi.WmiTooManyInstances(className):
            try:
                DispWmiReferences(grph, wmiInstanceNode, objWmi, cgiMoniker)
            except:
                exc = sys.exc_info()[1]
                sys.stderr.write("entity_wmi.py Exception=%s\n" % str(exc))
        else:
            # Prefixc with a dot so it is displayed first.
            grph.add((wmiInstanceNode, lib_common.MakeProp(".REFERENCES"),
                      lib_common.NodeLiteral("DISABLED")))

        # Displaying the associators is conditional because it slows things.
        # TODO: How to select this option with D3 ?????
        if displayAssociators:
            # This class appears everywhere, so not not display its references, it would be too long.
            if className == "Win32_ComputerSystem":
                grph.add((wmiInstanceNode, lib_common.MakeProp(".ASSOCIATORS"),
                          lib_common.NodeLiteral("DISABLED")))
            else:
                DisplayObjectAssociators(grph, wmiInstanceNode, objWmi,
                                         cgiMoniker)

    # Adds the class node to the instance.
    wmiClassNode = lib_wmi.WmiAddClassNode(grph, connWmi, wmiInstanceNode,
                                           wmiHost, nameSpace, className,
                                           lib_common.MakeProp(className))

    # Now displays the base class, up to the top.
    lib_wmi.WmiAddBaseClasses(grph, connWmi, wmiClassNode, wmiHost, nameSpace,
                              className)

    # Now tries to find the equivalent object in the Survol terminology.
    AddSurvolObjectFromWmi(grph, wmiInstanceNode, connWmi, className, objList)

    # TODO: Embetant car il faut le faire pour toutes les classes.
    # Et en plus on perd le nom de la propriete.
    # cgiEnv.OutCgiRdf("LAYOUT_RECT",['root\\cimv2:CIM_Datafile'])
    # 'PartComponent' for 'root\\cimv2:CIM_Datafile'
    # 'Element' for 'root\\cimv2:Win32_DCOMApplication'
    # 'Antecedent' for 'CIM_DataFile'
    cgiEnv.OutCgiRdf("LAYOUT_TWOPI", [
        lib_common.MakeProp('PartComponent'),
        lib_common.MakeProp('Element'),
        lib_common.MakeProp('Antecedent')
    ])
コード例 #13
0
def ClassUrl(nskey, cimomUrl, classNam):
    wbemMoniker = BuildWbemMoniker(cimomUrl, nskey, classNam)
    wbemInstanceUrl = lib_util.EntityUrlFromMoniker(wbemMoniker, True)
    return wbemInstanceUrl
コード例 #14
0
def ClassUrl(nskey, hostnameWmi, classNam):
    wmiMoniker = BuildWmiMoniker(hostnameWmi, nskey, classNam)
    wmiInstanceUrl = lib_util.EntityUrlFromMoniker(wmiMoniker, True)
    return wmiInstanceUrl
コード例 #15
0
def WmiAllNamespacesUrl(hostnameWmi):
    wmiMoniker = BuildWmiMoniker(hostnameWmi)
    wmiInstanceUrl = lib_util.EntityUrlFromMoniker(wmiMoniker, True, True,
                                                   True)
    return wmiInstanceUrl