示例#1
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    config_nam = cgiEnv.m_entity_id_dict["Url"]
    nam_connection = cgiEnv.m_entity_id_dict["Connection"]

    node_manager = survol_rabbitmq_manager.MakeUri(config_nam)

    creds = lib_credentials.GetCredentials("RabbitMQ", config_nam)

    cl = Client(config_nam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    logging.debug("nam_connection=%s", nam_connection)

    nod_connection = survol_rabbitmq_connection.MakeUri(config_nam, nam_connection)

    grph.add((node_manager, lib_common.MakeProp("Connection"), nod_connection))

    try:
        connect_list = cl.get_connection(nam_connection)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for connect_key in connect_list:
        connect_val = connect_list[connect_key]

        if connect_key == "vhost":
            nod_v_host = survol_rabbitmq_vhost.MakeUri(config_nam, connect_val)
            grph.add((nod_connection, lib_common.MakeProp("Virtual host"), nod_v_host))
        elif connect_key == "user":
            nod_user = survol_rabbitmq_user.MakeUri(config_nam, connect_val)
            grph.add((nod_connection, lib_common.MakeProp("User"), nod_user))
        elif connect_key == "host":
            nod_host = lib_uris.gUriGen.HostnameUri(connect_val)
            grph.add((nod_connection, lib_common.MakeProp("Host"), nod_host))
        elif connect_key in ["name", "peer_host", "peer_port"]:
            pass
        else:
            if isinstance(connect_val, six.string_types):
                connect_val = connect_val.replace(">", "@")

                logging.debug("connect_key=%s connect_val=%s", connect_key, connect_val)
            elif isinstance(connect_val, dict):
                pass
            elif isinstance(connect_val, tuple):
                pass
            elif isinstance(connect_val, list):
                pass
            else:
                pass

            logging.debug("Literal=%s", lib_util.NodeLiteral(connect_val))

            grph.add((nod_connection, lib_common.MakeProp(connect_key), lib_util.NodeLiteral(connect_val)))

    survol_rabbitmq_connection.AddSockets(grph, nod_connection, nam_connection)

    cgiEnv.OutCgiRdf()
示例#2
0
def _add_info_from_import(grph, package_node, package_key):
    """Displays general information about the module."""
    try:
        the_module = importlib.import_module(package_key)
    except ImportError:
        lib_common.ErrorMessageHtml("Importing %s: Error %s" %
                                    (package_key, str(sys.exc_info())))

    try:
        init_fil_nam = the_module.__file__
        fil_node = lib_uris.gUriGen.FileUri(init_fil_nam)
        grph.add((package_node, prop_python_package, fil_node))
    except AttributeError:
        pass

    try:
        txt_doc = the_module.__doc__
        if txt_doc:
            txt_doc = txt_doc.strip()
            grph.add((package_node, pc.property_information,
                      lib_util.NodeLiteral(txt_doc)))
    except AttributeError:
        pass

    props_package = {"Author": "__author__", "Version": "__version__"}

    for key_prop in props_package:
        val_prop = props_package[key_prop]
        try:
            txt_val = getattr(the_module, val_prop)
            if txt_val:
                grph.add((package_node, lib_common.MakeProp(key_prop),
                          lib_util.NodeLiteral(txt_val)))
        except AttributeError:
            pass
示例#3
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    for lin_cg in open("/proc/cgroups"):
        # Just in case there would be a comment.
        lin_cg = lin_cg.strip()
        if lin_cg.startswith("#"):
            continue
        split_cg = lin_cg.split('\t')
        subsys_name = split_cg[0]
        hierarchy = split_cg[1]
        num_cgroups = split_cg[2]
        enabled = split_cg[3]

        cgrp_node = survol_cgroup.MakeUri(subsys_name)
        grph.add((cgrp_node, lib_common.MakeProp("Hierarchy"),
                  lib_util.NodeLiteral(hierarchy)))
        grph.add((cgrp_node, lib_common.MakeProp("Num CGroups"),
                  lib_util.NodeLiteral(num_cgroups)))
        grph.add((cgrp_node, lib_common.MakeProp("Enabled"),
                  lib_util.NodeLiteral(enabled)))

    cgiEnv.OutCgiRdf()
示例#4
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)

    cimom_url = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    # There is no consensus on the WBEM class for namespaces,
    # so we have ours which must be correctly mapped.
    namespace_class = "wbem_namespace"
    root_node = lib_util.EntityUri(namespace_class, "")

    try:
        conn_wbem = lib_wbem.WbemConnection(cimom_url)
        nsd = lib_wbem.EnumNamespacesCapabilities(conn_wbem)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Namespaces from :" + cimom_url +
                                    " Caught:" + str(exc))

    # TODO: We should draw a namespaces tree but more examples needed.
    for nskey in nsd:

        cnt = nsd[nskey]
        wbem_url = lib_wbem.NamespaceUrl(nskey, cimom_url)
        wbem_node = lib_common.NodeUrl(wbem_url)

        grph.add((root_node, pc.property_cim_subnamespace, wbem_node))
        grph.add(
            (wbem_node, pc.property_information, lib_util.NodeLiteral(nskey)))
        grph.add(
            (wbem_node, pc.property_information, lib_util.NodeLiteral(cnt)))

    cgiEnv.OutCgiRdf("LAYOUT_RECT")
示例#5
0
def DictServiceToNode(grph, service_dict, machine_name=None):
    # TODO: This is a process but not only. How to display that?
    service_name = service_dict['ServiceName']

    # NOTE: SOON, ALL ENTITIES WILL HAVE THEIR HOSTNAME.
    if machine_name in [None, ""]:
        node_service = lib_uris.gUriGen.ServiceUri(service_name)
    else:
        node_service = lib_common.RemoteBox(machine_name).ServiceUri(service_name)

    try:
        current_state_idx = service_dict['CurrentState']
        current_state_nam = _state_dictionary[current_state_idx]
    except KeyError:
        current_state_nam = "Unknown state key"
    except IndexError:
        current_state_nam = "Unknown state index"

    grph.add((node_service, pc.property_information, lib_util.NodeLiteral(service_dict['DisplayName'])))
    # TODO: Change color with the state. ASSOCIATE COLOR TO PAIRS (Property + Literal value) ? SPECIALLY CODED VALUE WITH HTML TAGS ?

    service_pid = service_dict['ProcessId']

    # Display is as compact as possible to help routing. Informaitonal only.
    if service_pid != 0:
        # TODO: Plutot mettre un lien vers le process mais afficher comme un literal.
        state_string = str(service_pid) + "/" + current_state_nam
        # grph.add((node_service, pc.property_pid, lib_util.NodeLiteral(service_pid)))
        grph.add((node_service, pc.property_pid, lib_util.NodeLiteral(state_string)))
    else:
        # grph.add((node_service, pc.property_service_state, lib_util.NodeLiteral(current_state_nam)))
        grph.add((node_service, pc.property_service_state, lib_util.NodeLiteral(current_state_nam)))
    return node_service
示例#6
0
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    try:
        procid = int(cgiEnv.GetId())
    except Exception:
        lib_common.ErrorMessageHtml("Must provide a pid")

    objProc = CIM_Process.PsutilGetProcObj(procid)

    envProp = lib_common.MakeProp("environment")

    try:
        # Psutil version after 4.0.0
        envsDict = objProc.environ()
    except:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Error:" + str(exc))

    node_process = lib_common.gUriGen.PidUri(procid)

    for envKey in envsDict:
        envVal = envsDict[envKey]
        DEBUG("envKey=%s envVal=%s", envKey, envVal)
        nodeEnvNam = lib_util.NodeLiteral(envKey)

        # When a file or a directory displayed with a node,
        # its name is shortened so it can fit into the table.,
        # so it is less visible.

        # Some are probably for Windows only.
        if envKey in ["PATH", "PSMODULEPATH", "PYPATH"]:
            valSplit = envVal.split(os.pathsep)
            nodFilArr = [
                lib_common.gUriGen.DirectoryUri(filNam) for filNam in valSplit
            ]
            nodFilArrNod = lib_util.NodeLiteral(nodFilArr)
            #for filNam in valSplit:
            #	nodFil = lib_common.gUriGen.DirectoryUri(filNam)
            grph.add((nodeEnvNam, pc.property_rdf_data_nolist2, nodFilArrNod))
        elif os.path.isdir(envVal):
            nodFil = lib_common.gUriGen.DirectoryUri(envVal)
            #grph.add((nodeEnvNam,pc.property_directory,nodFil))
            grph.add((nodeEnvNam, pc.property_rdf_data_nolist2, nodFil))
        elif os.path.exists(envVal):
            nodFil = lib_common.gUriGen.FileUri(envVal)
            grph.add((nodeEnvNam, pc.property_rdf_data_nolist2, nodFil))
            #grph.add((nodeEnvNam,pc.property_directory,nodFil))
        else:
            # TODO: Beware that "\L" is transformed into "<TABLE>" by Graphviz !!!
            envValClean = envVal.replace(">", "_").replace("<", "_").replace(
                "&", "_").replace("\\", "_")
            nodeEnvValue = lib_util.NodeLiteral(envValClean)
            grph.add((nodeEnvNam, pc.property_rdf_data_nolist2, nodeEnvValue))
        grph.add((node_process, envProp, nodeEnvNam))

    # cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_directory,envProp])
    cgiEnv.OutCgiRdf("LAYOUT_RECT", [envProp])
def Main():
    paramkey_extensive_scan = "Extensive scan"

    # Beware that unchecked checkboxes are not posted, i.e. boolean variables set to False.
    # http://stackoverflow.com/questions/1809494/post-the-checkboxes-that-are-unchecked
    cgiEnv = lib_common.ScriptEnvironment(
        parameters={paramkey_extensive_scan: False})
    pidint = int(cgiEnv.GetId())

    grph = cgiEnv.GetGraph()

    paramExtensiveScan = cgiEnv.get_parameters(paramkey_extensive_scan)

    # By default, uses a small map of possible connection strings keyword.
    # Otherwise it is very slow to scan the whole process memory.
    if paramExtensiveScan:
        rgx_dsn = survol_odbc.regex_odbc_heavy
    else:
        rgx_dsn = survol_odbc.regex_odbc_light

    aggreg_dsns = _get_aggreg_dsns(pidint, rgx_dsn)

    node_process = lib_uris.gUriGen.PidUri(pidint)

    # TODO: Add a parameter to choose between light and heavy connection string definition.

    # TODO: Eliminate aggregated strings containing one or two tokens,
    # because they cannot be genuine DSNs.
    # 29812569: SERVER=\MYMACHINE
    # 34515016: Driver={SQL Server};Server=.\SQLEXPRESS;Database=ExpressDB;Trusted_Connection=yes
    # 34801013: SERVER=\MYMACHINE
    # 35634904: Driver={SQL Server};Server=.\SQLEXPRESS;Database=ExpressDB;Trusted_Connection=yes

    for aggreg_offset in aggreg_dsns:
        # Do not take the character before the keyword.
        aggreg_dsn_raw = aggreg_dsns[aggreg_offset]

        # Replaces all non-printable characters by spaces.
        # This should be done now by the regular expressions, but better be sure.
        aggreg_dsn = re.sub(b'[\x00-\x1f\x7f-\xff]+', b' ', aggreg_dsn_raw)

        # This should contain Ascii, convertible to UTF-8, but if the regular expression catch something else,
        # this decode throw: 'utf-8' codec can't decode bytes in position 3768-3769: invalid continuation byte.
        aggreg_dsn = aggreg_dsn.decode("utf-8", "ignore")
        dsn_full = str(aggreg_offset) + ": " + aggreg_dsn
        logging.debug("aggreg_offset=%s dsn_full=%s", aggreg_offset, dsn_full)
        grph.add((node_process, pc.property_information,
                  lib_util.NodeLiteral(dsn_full)))

        ### NO! Confusion between DSN and connection string.
        # All the existing code does: ODBC_ConnectString = survol_odbc_dsn.MakeOdbcConnectionString(dsnNam)
        # which basically creates "DSN=dsvNam;PWD=..." but here we already have the connection string.
        # TODO: Should we assimilate both ???
        node_dsn = survol_odbc_dsn.MakeUri(aggreg_dsn)
        grph.add((node_process, pc.property_odbc_dsn, node_dsn))
        # Fix this message.
        grph.add((node_dsn, pc.property_odbc_driver,
                  lib_util.NodeLiteral("ODBC driver")))

    cgiEnv.OutCgiRdf()
示例#8
0
def WbemKeyValues(key_value_items, display_none_values=False):
    """This is conceptually similar to WmiKeyValues"""
    dict_key_values = {}
    for wbem_key_name, wbem_value_literal in key_value_items:
        wbem_property = lib_properties.MakeProp(wbem_key_name)
        if isinstance(wbem_value_literal, lib_util.scalar_data_types):
            wbem_value_node = lib_util.NodeLiteral(wbem_value_literal)
        elif isinstance(wbem_value_literal, (tuple)):
            tuple_joined = " ; ".join(wbem_value_literal)
            wbem_value_node = lib_util.NodeLiteral(tuple_joined)
        elif wbem_value_literal is None:
            if display_none_values:
                wbem_value_node = lib_util.NodeLiteral("None")
        else:
            wbem_value_node = lib_util.NodeLiteral(
                "type=" + str(type(wbem_value_literal)) + ":" +
                str(wbem_value_literal))
            #try:
            #    refMoniker = str(wbem_value_literal.path())
            #    instance_url = lib_util.EntityUrlFromMoniker(refMoniker)
            #    wbem_value_node = lib_common.NodeUrl(instance_url)
            #except AttributeError as exc:
            #    wbem_value_node = lib_util.NodeLiteral(str(exc))

        dict_key_values[wbem_property] = wbem_value_node
    return dict_key_values
示例#9
0
def _add_info_from_pip(grph, node, package_key):
    """Each entity can have such a file with its name as file name.
    Then in its file, by convention adds information to a node."""
    try:
        # TODO: What about several Python versions ?
        installed_packages = lib_python.PipGetInstalledDistributions()

        # TODO: Maybe the version should be part of the key.
        for pckg in installed_packages:
            if package_key == pckg.key:
                _fill_one_package(grph, node, pckg)
            else:
                for sub_req in pckg.requires():
                    if sub_req.key == package_key:
                        subNode = MakeUri(pckg.key)
                        # [('>=', '4.0.0')]+[]+[('>=','4.0')]+[]
                        a_specs = sub_req.specs
                        if a_specs:
                            # TODO: This should be displayed on the edge !!!
                            grph.add(
                                (node,
                                 lib_common.MakeProp("Condition " + pckg.key),
                                 lib_util.NodeLiteral(str(a_specs))))
                        grph.add((subNode, prop_python_requires, node))
                        break

    except Exception as exc:
        grph.add(
            (node, pc.property_information, lib_util.NodeLiteral(str(exc))))
示例#10
0
def AddFileProperties(grph, current_node, current_filename):
    try:
        import win32api
        import lib_win32

        prop_dict = lib_win32.getFileProperties(current_filename)
        for prp, val in prop_dict.items():
            val = prop_dict[prp]
            if val is None:
                continue

            if isinstance(val, dict):
                val = json.dumps(val)
                # TODO: Unicode error encoding=ascii
                # 169    251    A9    10101001    "Copyright"    &#169;    &copy;    Copyright sign
                # Might contain this: "LegalCopyright Copyright \u00a9 2010"
                val = val.replace("\\", "\\\\")
            grph.add((current_node, lib_common.MakeProp(prp), lib_util.NodeLiteral(val)))
    except ImportError:
        pass

    file_mime_type = lib_mime.filename_to_mime(current_filename)
    if file_mime_type:
        if file_mime_type[0]:
            grph.add((current_node, lib_common.MakeProp("Mime type"), lib_util.NodeLiteral(str(file_mime_type))))
示例#11
0
def Main():
    # If this flag is set, the script uses SLP to discover WBEM Agents.
    paramkey_slp = "Service Location Protocol"

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

    flag_slp = bool(cgiEnv.get_parameters(paramkey_slp))

    grph = cgiEnv.GetGraph()

    _wbem_servers_display(grph)

    if flag_slp:
        dict_services = survol_neighborhood.GetSLPServices("survol")
        for key_service in dict_services:
            wbem_node = _add_from_wbem_cimom(grph, key_service)

            if not wbem_node:
                continue

            grph.add((wbem_node, pc.property_information, lib_util.NodeLiteral("Service Location Protocol")))

            attrs_service = dict_services[key_service]
            for key_attr in attrs_service:
                prop_attr = lib_common.MakeProp(key_attr)
                val_attr = attrs_service[key_attr]
                grph.add((wbem_node, prop_attr, lib_util.NodeLiteral(val_attr)))

    cgiEnv.OutCgiRdf()
示例#12
0
def Main():

    cgiEnv = lib_common.ScriptEnvironment()

    configNam = cgiEnv.GetId()

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    # >>> cl.get_all_vhosts()
    # http://localhost:12345/api/vhosts
    # [{u'name': u'/', u'tracing': False, u'messages_details': {u'rate': 0.0}, u'messages': 0, u'message_stats': {u'deliver_no_ack': 0, u'
    # publish_out': 0, u'get_no_ack': 13, u'return_unroutable': 0, u'confirm': 0, u'deliver_get': 13, u'publish': 13, u'confirm_details':
    # {u'rate': 0.0}, u'ack_details': {u'rate': 0.0}, u'get': 0, u'deliver': 0, u'publish_out_details': {u'rate': 0.0}, u'redeliver_detail
    # s': {u'rate': 0.0}, u'deliver_details': {u'rate': 0.0}, u'deliver_get_details': {u'rate': 0.0}, u'publish_details': {u'rate': 0.0},
    # u'publish_in_details': {u'rate': 0.0}, u'ack': 0, u'publish_in': 0, u'return_unroutable_details': {u'rate': 0.0}, u'get_details': {u
    # 'rate': 0.0}, u'get_no_ack_details': {u'rate': 0.0}, u'deliver_no_ack_details': {u'rate': 0.0}, u'redeliver': 0}, u'messages_unackno
    # wledged_details': {u'rate': 0.0}, u'messages_ready_details': {u'rate': 0.0}, u'messages_unacknowledged': 0, u'messages_ready': 0}]

    try:
        #
        listVHosts = cl.get_all_vhosts()
    except Exception as exc:
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for objVHost in listVHosts:
        namVHost = objVHost["name"]
        logging.debug("q=%s", namVHost)

        nodeVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)

        try:
            grph.add((nodeVHost, lib_common.MakeProp("tracing"),
                      lib_util.NodeLiteral(objVHost["tracing"])))
        except KeyError:
            pass

        try:
            grph.add((nodeVHost, lib_common.MakeProp("messages"),
                      lib_util.NodeLiteral(objVHost["messages"])))
        except KeyError:
            pass

        # http://127.0.0.1:12345/#/vhosts//
        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "vhosts",
                                                     namVHost)

        grph.add((nodeVHost, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodeManager, lib_common.MakeProp("Virtual host"), nodeVHost))

    cgiEnv.OutCgiRdf()
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    for part in psutil.disk_partitions():
        # partition(device='D:\\\\', mountpoint='D:\\\\', fstype='NTFS', opts='rw,fixed')
        logging.debug("device=%s fstype=%s", part.device, part.fstype)
        logging.debug("All=%s", str(part))

        # BEWARE: This is not very clear.
        if lib_util.isPlatformWindows:
            # sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed')
            # DeviceID     : X:
            # DriveType    : 4
            # ProviderName : \\192.168.1.81\jsmith
            # FreeSpace    : 170954825728
            # Size         : 2949169561600
            # VolumeName   : jsmith
            #
            # WMI does not want a backslash at the end: "C:".
            # Replacing backslashes is necessary on Windows.
            partition_name = part.device.replace('\\', '')

            # We could as well take "Win32_LogicalDisk" because it inherits from "CIM_LogicalDisk"
            node_partition = lib_uris.gUriGen.node_from_args(
                "CIM_LogicalDisk", partition_name)
        else:
            # The class CIM_LogicalDisk represents a contiguous range of logical blocks
            # that is identifiable by a FileSystem via the Disk's DeviceId (key) field.
            # Each storage extent with the capability of or already hosting a file system
            # is represented as a sub-class of CIM_LogicalDisk.
            # The class CIM_LogicalDisk is the connector between File Systems and Storage Extents

            # [sdiskpart(device='/dev/vda1', mountpoint='/var/lib/docker/containers',
            #            fstype='ext4', opts='rw,seclabel,relatime,data=ordered'),]

            # This does not really work on Windows because WMI expects
            # something like 'Win32_DiskPartition.DeviceID="Disk #0.Partition #0"'
            partition_name = part.device

            node_partition = lib_uris.gUriGen.DiskPartitionUri(partition_name)

        mount_point = part.mountpoint.replace('\\', '/')
        node_mount = lib_uris.gUriGen.DirectoryUri(mount_point)

        # TODO: Check this list.
        if part.fstype != "":
            # partition(device='T:\\\\', mountpoint='T:\\\\', fstype='', opts='cdrom')
            grph.add((node_partition, pc.property_file_system_type,
                      lib_util.NodeLiteral(part.fstype)))
            grph.add((node_mount, pc.property_mount, node_partition))

        if part.opts != "":
            grph.add((node_mount, pc.property_mount_options,
                      lib_util.NodeLiteral(part.opts)))

    cgiEnv.OutCgiRdf()
示例#14
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    dsn_nam = cgiEnv.m_entity_id_dict["Dsn"]

    logging.debug("dsn=(%s)", dsn_nam)

    odbc_connect_string = survol_odbc_dsn.MakeOdbcConnectionString(dsn_nam)
    try:
        cnxn = pyodbc.connect(odbc_connect_string)
        logging.debug("Connected: %s", dsn_nam)
        cursor_queries = cnxn.cursor()

        qry_queries = """
            SELECT sqltext.TEXT,
            req.session_id,
            req.status,
            sess.host_process_id,
            sess.host_name
            FROM sys.dm_exec_requests req
            CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
            , sys.dm_exec_sessions sess
            where sess.session_id = req.session_id
        """

        prop_sql_server_sql_query = lib_common.MakeProp("Sql query")
        prop_sql_server_host_process = lib_common.MakeProp("Host process")
        prop_sql_server_status = lib_common.MakeProp("Status")

        for row_qry in cursor_queries.execute(qry_queries):
            logging.debug("row_qry.session_id=(%s)", row_qry.session_id)
            node_session = session.MakeUri(dsn_nam, row_qry.session_id)

            # A bit of cleanup.
            query_clean = row_qry.TEXT.replace("\n", " ").strip()

            # TODO: Must add connection information so we can go from the tables to sqlserver itself.
            node_sql_query = sql_query_module.MakeUri(query_clean, dsn_nam)
            grph.add((node_session, prop_sql_server_sql_query, node_sql_query))
            node_process = lib_common.RemoteBox(row_qry.host_name).PidUri(
                row_qry.host_process_id)
            grph.add((node_process, pc.property_pid,
                      lib_util.NodeLiteral(row_qry.host_process_id)))

            grph.add(
                (node_session, prop_sql_server_host_process, node_process))
            grph.add((node_session, prop_sql_server_status,
                      lib_util.NodeLiteral(row_qry.status)))

    except Exception as exc:
        lib_common.ErrorMessageHtml("nodeDsn=%s Unexpected error:%s" %
                                    (dsn_nam, str(exc)))

    cgiEnv.OutCgiRdf()
示例#15
0
    def add_file_owner_windows():
        try:
            import win32api
            import win32con
            import win32security
        except ImportError:
            return 

        from sources_types import Win32_UserAccount
        from sources_types import Win32_Group

        def SID_CodeToName(typeSID):
            mapSIDList = {
                win32security.SidTypeUser: "******",
                win32security.SidTypeGroup: "Group SID",
                win32security.SidTypeDomain: "Domain SID",
                win32security.SidTypeAlias: "Alias SID",
                win32security.SidTypeWellKnownGroup: "Well-known group",
                win32security.SidTypeDeletedAccount: "Deleted account",
                win32security.SidTypeInvalid: "Invalid SID",
                win32security.SidTypeUnknown: "Unknown type SID",
                win32security.SidTypeComputer: "Computer SID",
                # win32security.SidTypeLabel: "Mandatory integrity label SID" # NOT DEFINED
            }

            try:
                return mapSIDList[typeSID]
            except:
                return "Unknown SID"

        try:
            sd = win32security.GetFileSecurity (file_name, win32security.OWNER_SECURITY_INFORMATION)
        except Exception as exc:
            msg = str(exc)
            grph.add((file_node, pc.property_owner, lib_util.NodeLiteral(msg)))
            return

        owner_sid = sd.GetSecurityDescriptorOwner ()
        account_name, domain_name, typeCode = win32security.LookupAccountSid(None, owner_sid)
        typ_nam = SID_CodeToName(typeCode)
        logging.debug("Domain=%s Name=%s Type=%s", domain_name, account_name, typ_nam)

        if typeCode == win32security.SidTypeUser:
            account_node = Win32_UserAccount.MakeUri(account_name, domain_name)
        elif typeCode == win32security.SidTypeGroup:
            account_node = Win32_Group.MakeUri(account_name, domain_name)
        elif typeCode == win32security.SidTypeWellKnownGroup:
            account_node = Win32_Group.MakeUri(account_name, domain_name)
        else:
            # What else can we do ?
            account_node = Win32_UserAccount.MakeUri(account_name, domain_name)

        # TODO: What can we do with the domain ?
        grph.add((account_node, lib_common.MakeProp("Domain"), lib_util.NodeLiteral(domain_name)))
        grph.add((account_node, lib_common.MakeProp("SID"), lib_util.NodeLiteral(typ_nam)))
        grph.add((file_node, pc.property_owner, account_node))
示例#16
0
def DisplayMappedProcesses(grph, file_name):
    """This displays all processes mapping a given filename.
    This simply iterates on processes, then on mapped files of each process.
    This is not very efficient but there is no other way."""
    grph.add((lib_common.nodeMachine, pc.property_hostname,
              lib_util.NodeLiteral(lib_util.currentHostname)))

    # This is also a file mapped into memory.
    uri_mapped_file = lib_uris.gUriGen.FileUri(file_name)

    uri_mem_map = None

    try:
        statinfo = os.stat(file_name)
    except Exception as exc:
        grph.add((uri_mapped_file, lib_common.MakeProp("Error"),
                  lib_util.NodeLiteral(str(exc))))
        return

    file_size = lib_util.AddSIUnit(statinfo.st_size, "B")
    grph.add((uri_mapped_file, pc.property_file_size,
              lib_util.NodeLiteral(file_size)))

    prop_memory_rss = lib_common.MakeProp("Resident Set Size")
    for proc in psutil.process_iter():
        pid = proc.pid

        try:
            all_maps = proc.memory_maps()
        except Exception as exc:
            # Probably psutil.AccessDenied
            continue

        for the_map in all_maps:
            # This, because all Windows paths are "standardized" by us.
            same_fil = lib_util.standardized_file_path(
                the_map.path) == lib_util.standardized_file_path(file_name)

            if same_fil:
                # Maybe this is the first mapping we have found.
                if uri_mem_map == None:
                    uri_mem_map = lib_uris.gUriGen.MemMapUri(file_name)
                    grph.add(
                        (uri_mapped_file, pc.property_mapped, uri_mem_map))
                node_process = lib_uris.gUriGen.PidUri(pid)

                # The property is reversed because of display.
                grph.add((uri_mem_map, pc.property_memmap, node_process))
                grph.add(
                    (node_process, pc.property_pid, lib_util.NodeLiteral(pid)))

                # Displays the RSS only if different from the file size.
                if the_map.rss != statinfo.st_size:
                    grph.add((node_process, prop_memory_rss,
                              lib_util.NodeLiteral(the_map.rss)))
示例#17
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)
    machine_name = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    if lib_util.is_local_address(machine_name):
        mach_name_or_none = None
        server_box = lib_uris.gUriGen
    else:
        mach_name_or_none = machine_name
        server_box = lib_uris.RemoteBox(machine_name)

    try:
        login_implicit = False  # IF FACT, WHY SHOULD IT BE SET ????????
        if login_implicit or mach_name_or_none is None:
            cnnct = wmi.WMI(machine_name)
        else:
            # persistent net connection
            # This works:
            # >>> c = wmi.WMI(wmi=wmi.connect_server(server='Titi', namespace="/root/cimv2", user='******', password='******'))

            logging.debug("Explicit WMI connection machine_name=%s",
                          machine_name)

            cnnct = lib_wmi.WmiConnect(machine_name, "/root/cimv2")
    except Exception as exc:
        lib_common.ErrorMessageHtml("WMI " + machine_name + " partitions:" +
                                    str(exc))

    for physical_disk in cnnct.Win32_DiskDrive():
        node_disk = server_box.DiskUri(physical_disk.Name.replace('\\', '/'))
        grph.add((node_disk, pc.property_information,
                  lib_util.NodeLiteral(physical_disk.MediaType)))

        for partition in physical_disk.associators(
                "Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators(
                    "Win32_LogicalDiskToPartition"):
                # BEWARE: What we call partition is in fact a logical disk.
                # This is not really important for this application,
                # as long as there are two levels in a disk description.
                node_partition = server_box.DiskPartitionUri(logical_disk.Name)
                grph.add((node_partition, pc.property_information,
                          lib_util.NodeLiteral(logical_disk.Description)))

                grph.add((node_partition, pc.property_file_system_type,
                          lib_util.NodeLiteral(logical_disk.FileSystem)))

                # The logical disk name is the same as the mount point.
                grph.add((node_partition, pc.property_partition, node_disk))
                grph.add((server_box.DirectoryUri(logical_disk.Name),
                          pc.property_mount, node_partition))

    cgiEnv.OutCgiRdf()
def Main():

    cgiEnv = lib_common.ScriptEnvironment()

    # "NtOpenObjectAuditAlarm%40C%3A\windows\system32\ntdll.dll"
    # Filename is optional.

    # The symbol is already demangled.
    symbol_nam = cgiEnv.m_entity_id_dict["Name"]
    fil_nam = cgiEnv.m_entity_id_dict["File"]

    logging.debug("symbol=%s fil_nam=%s", symbol_nam, fil_nam)

    grph = cgiEnv.GetGraph()

    sym_node = lib_uris.gUriGen.SymbolUri(symbol_nam, fil_nam)

    if fil_nam:
        fil_node = lib_uris.gUriGen.FileUri( fil_nam )
        grph.add((fil_node, pc.property_symbol_defined, sym_node))
        vers_str = lib_win32.VersionString(fil_nam)
        grph.add((fil_node, pc.property_information, lib_util.NodeLiteral(vers_str)))

        sym = FindPESymbol(fil_nam, symbol_nam)

        if sym is not None:
            # Non-breaking space: A0    10100000         &#160;    &nbsp;
            doc_txt = getattr(sym, "__doc__")

            # This string is filled with spaces and CR which are translated into "&#160;".
            doc_txt = re.sub(r'\s+', ' ', doc_txt).strip()

            grph.add((sym_node, pc.property_information,lib_util.NodeLiteral(doc_txt)))

            # Possible values are "name","offset","ordinal","forwarder"
            try:
                fwrd = getattr(sym, "forwarder")
                grph.add((sym_node, lib_common.MakeProp("Forwarder"), lib_util.NodeLiteral(fwrd)))
            except:
                pass

            try:
                fwrd = getattr(sym,"ordinal")
                grph.add((sym_node, lib_common.MakeProp("Ordinal"), lib_util.NodeLiteral(fwrd)))
            except:
                pass

            ful_nam, lst_args = lib_symbol.SymToArgs(symbol_nam)
            if lst_args:
                for arg in lst_args:
                    # TODO: Order of arguments must not be changed.
                    arg_node = lib_uris.gUriGen.ClassUri(arg, fil_nam)
                    grph.add((sym_node, pc.property_argument, arg_node))

    cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_argument])
示例#19
0
def _create_wbem_node(grph, root_node, entity_host, name_space, class_name,
                      entity_id):
    wbem_namespace = name_space.replace("\\", "/")
    wbem_servers_desc_list = lib_wbem.GetWbemUrls(entity_host, wbem_namespace,
                                                  class_name, entity_id)

    # If there are no servers.
    pair_name_node = None

    for url_server in wbem_servers_desc_list:
        wbem_node = lib_common.NodeUrl(url_server[0])
        grph.add((root_node, pc.property_wbem_data, wbem_node))

        wbemHostNode = lib_uris.gUriGen.HostnameUri(url_server[1])
        grph.add((wbem_node, pc.property_host, wbemHostNode))

        # TODO: Add a Yawn server ??
        grph.add((wbem_node, pc.property_wbem_server,
                  lib_util.NodeLiteral(url_server[1])))

        # Now adds the description of the class.
        try:
            conn_wbem = lib_wbem.WbemConnection(entity_host)
        except Exception as exc:
            logging.error("WbemConnection throw:%s" % str(exc))
            continue

        kla_descrip = lib_wbem.WbemClassDescription(conn_wbem, class_name,
                                                    wbem_namespace)
        ok_wbem_class = True
        if not kla_descrip:
            ok_wbem_class = False
            kla_descrip = "Undefined class %s %s" % (wbem_namespace,
                                                     class_name)
        grph.add((wbem_node, pc.property_information,
                  lib_util.NodeLiteral(kla_descrip)))

        # Maybe this class is not Known in WBEM.
        try:
            pair_name_node = _wbem_add_all_base_classes(
                grph, conn_wbem, wbem_node, entity_host, name_space,
                class_name)
        except:
            pair_name_node = None

        if ok_wbem_class and wbem_ok and name_space != "" and entity_host != "":
            namespace_url = lib_wbem.NamespaceUrl(name_space, entity_host,
                                                  class_name)
            namespace_node = lib_common.NodeUrl(namespace_url)
            grph.add((wbem_node, pc.property_information, namespace_node))

    # TODO: This is a bit absurd because we return just one list.
    return pair_name_node
示例#20
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()
    fname = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    fname_mystery_node = lib_uris.gUriGen.ComTypeLibUri(fname)

    # TODO: Difficulty, many entries.

    HLITypeKinds = {
            pythoncom.TKIND_ENUM      : 'Enumeration',
            pythoncom.TKIND_RECORD    : 'Record',
            pythoncom.TKIND_MODULE    : 'Module',
            pythoncom.TKIND_INTERFACE : 'Interface',
            pythoncom.TKIND_DISPATCH  : 'Dispatch',
            pythoncom.TKIND_COCLASS   : 'CoClass',
            pythoncom.TKIND_ALIAS     : 'Alias',
            pythoncom.TKIND_UNION     : 'Union'
      }


    try:
        tlb = pythoncom.LoadTypeLib(fname)
    except pythoncom.com_error:
        lib_common.ErrorMessageHtml("Cannot load:" + fname)

    for idx in range(tlb.GetTypeInfoCount()):
        try:
            info_typ = tlb.GetTypeInfoType(idx)

            typ_nam = HLITypeKinds[info_typ]

            sub_entity_type = lib_util.ComposeTypes("com", "type_lib_entry", typ_nam.lower())

            name_com_entry_uri = "%s_(%d)" % (fname, idx)

            # TODO: Maybe this will be cleaner. Quick and dirty solution for the moment.
            # UriNodeCreatorName = "ComTypeLibEntry" + typ_nam + "Uri"
            # funcCreate = getattr( lib_common, UriNodeCreatorName )
            # entry_node = funcCreate( "%s_(%d)" % ( fname, idx ) )
            entry_node = lib_util.EntityUri(sub_entity_type, name_com_entry_uri)

            name, doc, ctx, helpFile = tlb.GetDocumentation(idx)

            grph.add((entry_node, pc.property_information, lib_util.NodeLiteral("name=%s" % name)))
            grph.add((entry_node, pc.property_information, lib_util.NodeLiteral("type=%s" % typ_nam)))
            grph.add((fname_mystery_node, pc.property_com_entry, entry_node))

        except pythoncom.com_error as exc:
            lib_common.ErrorMessageHtml("Caught:" + exc)

    cgiEnv.OutCgiRdf("LAYOUT_RECT")
示例#21
0
def Main():

    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    dsn_nam = cgiEnv.m_entity_id_dict["Dsn"]

    logging.debug("dsn=(%s)", dsn_nam)

    node_dsn = survol_odbc_dsn.MakeUri(dsn_nam)

    odbc_connect_string = survol_odbc_dsn.MakeOdbcConnectionString(dsn_nam)

    try:
        cnxn = pyodbc.connect(odbc_connect_string)
        logging.debug("Connected: %s", dsn_nam)

        for prmstr in dir(pyodbc):
            if not prmstr.startswith("SQL_"):
                continue

            # Some keywords are not interesting. This is a bit arbitrary.
            if prmstr in ["SQL_KEYWORDS"]:
                continue

            nicestr = prmstr[4:].replace("_", " ").capitalize()

            prop = lib_common.MakeProp(nicestr)

            try:
                prm = getattr(pyodbc, prmstr)
            except:
                grph.add((node_dsn, prop, lib_util.NodeLiteral("Unavailable")))
                continue

            try:
                prm_value = cnxn.getinfo(prm)
            except:
                continue

            try:
                grph.add((node_dsn, prop, lib_util.NodeLiteral(prm_value)))
            except Exception as exc:
                txt = str(exc)
                grph.add((node_dsn, prop, lib_util.NodeLiteral(txt)))
                continue

    except Exception as exc:
        lib_common.ErrorMessageHtml("node_dsn=%s Unexpected error:%s" %
                                    (dsn_nam, str(exc)))

    cgiEnv.OutCgiRdf()
示例#22
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()
    user_name_with_host = cgiEnv.GetId()

    # Usernames have the syntax user@host
    user_split = user_name_with_host.split('@')
    user_name = user_split[0]

    if len(user_split) > 1:
        user_host = user_split[1]
        if user_host != lib_util.currentHostname:
            # TODO: Should interrogate other host with "finger" protocol.
            lib_common.ErrorMessageHtml(
                "Cannot get user properties on different host:" + user_host)

    if not user_name:
        lib_common.ErrorMessageHtml(
            "Linux username should not be an empty string")

    grph = cgiEnv.GetGraph()

    user_node = lib_uris.gUriGen.UserUri(user_name)

    # It runs this Linux command which returns a single line.
    id_cmd = ["id", user_name]

    id_pipe = lib_common.SubProcPOpen(id_cmd)

    id_last_output, id_err = id_pipe.communicate()

    lines = id_last_output.split(b'\n')
    logging.debug("id=" + user_name + " lines=" + str(lines))

    # $ id my_user
    # uid=500(my_user) gid=500(guest) groupes=500(guest),81(audio)

    first_line = lines[0]

    first_split = split_id(first_line)

    user_id = parse_id_name(first_split[0])[0]

    grph.add((user_node, pc.property_userid, lib_util.NodeLiteral(user_id)))

    for grp_str in first_split[2].split(b','):
        group_id, group_name = parse_id_name(grp_str)
        grp_node = lib_uris.gUriGen.GroupUri(group_name)
        grph.add(
            (grp_node, pc.property_groupid, lib_util.NodeLiteral(group_id)))
        grph.add((user_node, pc.property_group, grp_node))

    cgiEnv.OutCgiRdf()
示例#23
0
def Main():

	cgiEnv = lib_common.ScriptEnvironment()

	configNam = cgiEnv.GetId()

	nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

	creds = lib_credentials.GetCredentials( "RabbitMQ", configNam )

	# cl = Client('localhost:12345', 'guest', 'guest')
	cl = Client(configNam, creds[0], creds[1])

	grph = cgiEnv.GetGraph()

	# cl.is_alive()

	#>>> cl.get_users()
	#[{u'hashing_algorithm': u'rabbit_password_hashing_sha256', u'name': u'guest', u'tags': u'administrator', u'password_hash': u'xxxxxx'}]
	try:
		#
		listUsers = cl.get_users()
	except:
		#
		exc = sys.exc_info()[1]
		lib_common.ErrorMessageHtml("Caught:"+str(exc))

	for objUser in listUsers:
		namUser = objUser["name"]
		logging.debug("q=%s",namUser)

		nodeUser = survol_rabbitmq_user.MakeUri(configNam,namUser)

		try:
			grph.add( ( nodeUser, lib_common.MakeProp("Tags"), lib_util.NodeLiteral(objUser["tags"]) ) )
		except KeyError:
			pass

		try:
			grph.add( ( nodeUser, lib_common.MakeProp("Hashing algorithm"), lib_util.NodeLiteral(objUser["hashing_algorithm"]) ) )
		except KeyError:
			pass

		# http://127.0.0.1:12345/#/users/guest
		managementUrl = rabbitmq.ManagementUrlPrefix(configNam,"users",namUser)

		grph.add( ( nodeUser, lib_common.MakeProp("Management"), lib_common.NodeUrl(managementUrl) ) )

		grph.add( ( nodeManager, lib_common.MakeProp("User"), nodeUser ) )


	cgiEnv.OutCgiRdf()
def DoRemote(grph, cimomSrv):
    import wmi
    # TODO: Add the host address to the connection.
    # TODO: Cache for the connection ?
    # wmi_cnnct = wmi.WMI(cimomSrv)
    wmi_cnnct = wmi.WMI()

    # TODO: This works but is very slow (About 30 seconds).
    for win_prod in wmi_cnnct.Win32_Product():
        # instance of Win32_Product
        # {
        #         AssignmentType = 1;
        #         Caption = "Microsoft Web Deploy 3.5";
        #         Description = "Microsoft Web Deploy 3.5";
        #         IdentifyingNumber = "{69A998C5-00A9-42CA-AB4E-C31CFFCD9251}";
        #         InstallDate = "20150709";
        #         InstallSource = "C:\\ProgramData\\Package Cache\\{69A998C5-00A9-42CA-AB4E-C31CFFCD9251}v3.1237.1763\\packages\\WebDeploy\\";
        #
        #         InstallState = 5;
        #         Language = "1033";
        #         LocalPackage = "C:\\windows\\Installer\\8a43794.msi";
        #         Name = "Microsoft Web Deploy 3.5";
        #         PackageCache = "C:\\windows\\Installer\\8a43794.msi";
        #         PackageCode = "{28DAC33F-DD0E-4293-9BB0-5585B4D89CB9}";
        #         PackageName = "WebDeploy_x64.msi";
        #         Vendor = "Microsoft Corporation";
        #         Version = "3.1237.1763";
        #         WordCount = 2;
        # };
        # {69A998C5-00A9-42CA-AB4E-C31CFFCD9251}
        # Product(Language=u'1033', ProductName=u'Microsoft Web Deploy 3.5', PackageCode=u'{28DAC33F-DD0E-4293-9BB0-5585B4D89CB9}', Transforms
        # =u'', AssignmentType=u'1', PackageName=u'WebDeploy_x64.msi', InstalledProductName=u'Microsoft Web Deploy 3.5', VersionString=u'3.123
        # 7.1763', RegCompany=u'', RegOwner=u'', ProductID=u'', ProductIcon=u'C:\\windows\\Installer\\{69A998C5-00A9-42CA-AB4E-C31CFFCD9251}\\
        # MSDeployIcon.exe', InstallLocation=u'', InstallSource=u'C:\\ProgramData\\Package Cache\\{69A998C5-00A9-42CA-AB4E-C31CFFCD9251}v3.123
        # 7.1763\\packages\\WebDeploy\\', InstallDate=u'20150709', Publisher=u'Microsoft Corporation', LocalPackage=u'C:\\windows\\Installer\\
        # 8a43794.msi', HelpLink=u'', HelpTelephone=u'', URLInfoAbout=u'', URLUpdateInfo=u'')

        try:
            product_node = Win32_Product.MakeUri(win_prod.Caption)
            grph.add((product_node, pc.property_information,
                      lib_util.NodeLiteral(win_prod.Description)))
            grph.add((product_node, lib_common.MakeProp("IdentifyingNumber"),
                      lib_util.NodeLiteral(win_prod.IdentifyingNumber)))
            Win32_Product.AddInstallSource(grph, product_node, win_prod)

            grph.add((lib_common.nodeMachine,
                      lib_common.MakeProp("Win32_Product"), product_node))

        except Exception as exc:
            lib_common.ErrorMessageHtml("Caught:%s" % str(exc))
示例#25
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    try:
        procid = int(cgiEnv.GetId())
    except Exception:
        lib_common.ErrorMessageHtml("Must provide a pid")

    obj_proc = CIM_Process.PsutilGetProcObj(procid)

    env_prop = lib_common.MakeProp("environment")

    try:
        envs_dict = obj_proc.environ()
    except Exception as exc:
        lib_common.ErrorMessageHtml("Caught:%s" % exc)

    node_process = lib_uris.gUriGen.PidUri(procid)

    for env_key in envs_dict :
        env_val = envs_dict[env_key]
        logging.debug("env_key=%s env_val=%s", env_key, env_val)
        node_env_nam = lib_util.NodeLiteral(env_key)

        # When a file or a directory displayed with a node,
        # its name is shortened so it can fit into the table.,
        # so it is less visible.

        # Some are probably for Windows only.
        if env_key in ["PATH", "PSMODULEPATH", "PYPATH"]:
            val_split = env_val.split(os.pathsep)
            nod_fil_arr = [lib_uris.gUriGen.DirectoryUri(fil_nam) for fil_nam in val_split]
            nod_fil_arr_nod = lib_util.NodeLiteral(nod_fil_arr)
            grph.add((node_env_nam, pc.property_rdf_data_nolist2, nod_fil_arr_nod))
        elif os.path.isdir(env_val):
            nod_fil = lib_uris.gUriGen.DirectoryUri(env_val)
            grph.add((node_env_nam, pc.property_rdf_data_nolist2, nod_fil))
        elif os.path.exists(env_val):
            nod_fil = lib_uris.gUriGen.FileUri(env_val)
            grph.add((node_env_nam, pc.property_rdf_data_nolist2, nod_fil))
        else:
            # TODO: Beware that "\L" is transformed into "<TABLE>" by Graphviz !!!
            env_val_clean = env_val.replace(">", "_").replace("<", "_").replace("&", "_").replace("\\", "_")
            node_env_value = lib_util.NodeLiteral(env_val_clean)
            grph.add((node_env_nam, pc.property_rdf_data_nolist2, node_env_value))
        grph.add((node_process, env_prop, node_env_nam))

    cgiEnv.OutCgiRdf("LAYOUT_RECT", [env_prop])
示例#26
0
def _add_default_nodes(grph, root_node, entity_host):
    logging.debug("_add_default_nodes entity_host=%s", entity_host)
    current_node_hostname = lib_uris.gUriGen.HostnameUri(
        lib_util.currentHostname)
    grph.add(
        (current_node_hostname, pc.property_information,
         lib_util.NodeLiteral("Current host:" + lib_util.currentHostname)))
    grph.add((root_node, pc.property_rdf_data_nolist2, current_node_hostname))

    curr_username = FunctionGetUser()
    current_node_user = lib_uris.gUriGen.UserUri(curr_username)
    grph.add((current_node_user, pc.property_information,
              lib_util.NodeLiteral("Current user:" + curr_username)))
    grph.add((root_node, pc.property_rdf_data_nolist2, current_node_user))
示例#27
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    prop_pid_path = lib_common.MakeProp("Process")
    prop_type = lib_common.MakeProp("Type")
    prop_state = lib_common.MakeProp("State")
    prop_inode = lib_common.MakeProp("INode")

    args = [
        "netstat",
        '-a',
        '--unix',
        '-p',
    ]
    pOpNetstat = lib_common.SubProcPOpen(args)

    netstat_last_output, netstat_err = pOpNetstat.communicate()

    asstr = netstat_last_output.decode("utf-8")

    # Do not read the header on the first four lines.
    for lin in asstr.split('\n')[4:]:
        try:
            sock_type = lin[25:36].strip()
            sock_state = lin[36:50].strip()
            sock_inode = lin[50:59].strip()
            sock_path = lin[80:].strip()
        except:
            logging.warning("Cannot parse:%s", lin)
            continue

        if sock_path:
            node_path = lib_uris.gUriGen.FileUri(sock_path)
            grph.add((node_path, prop_type, lib_util.NodeLiteral(sock_type)))
            grph.add((node_path, prop_state, lib_util.NodeLiteral(sock_state)))
            grph.add((node_path, prop_inode, lib_util.NodeLiteral(sock_inode)))

        sock_pid_prog = lin[59:80].strip()
        if sock_pid_prog not in ["-", ""]:
            sock_pid_prog_split = sock_pid_prog.split("/")
            sock_pid = sock_pid_prog_split[0]

            node_proc = lib_uris.gUriGen.PidUri(sock_pid)
            if sock_path:
                grph.add((node_path, prop_pid_path, node_proc))

    cgiEnv.OutCgiRdf()
def Main():
    cgiEnv = lib_common.ScriptEnvironment()
    pid_int = int(cgiEnv.GetId())

    pid_m_bean = cgiEnv.m_entity_id_dict["Handle"]

    # TODO: Not convenient.
    mbean_obj_nam = cgiEnv.m_entity_id_dict["Name"]
    mbean_obj_nam = mbean_obj_nam.replace("*", ",").replace("-", "=")

    grph = cgiEnv.GetGraph()

    node_process = lib_uris.gUriGen.PidUri(pid_int)

    jmx_data = survol_java.GetJavaDataFromJmx(pid_int, mbean_obj_nam)

    jmx_data_m_beans = jmx_data["allMBeans"]

    prop_m_bean = lib_common.MakeProp("MBean")

    # There should be only one.
    for jmx_m_bean in jmx_data_m_beans:
        cls_nam = jmx_m_bean["className"]
        obj_nam = jmx_m_bean["objectName"]

        if obj_nam != mbean_obj_nam:
            logging.error("THIS SHOULD NOT HAPPEN: %s != %s", obj_nam,
                          mbean_obj_nam)

        # "=sun.management.ManagementFactoryHelper$1[java.nio:type=BufferPool,name=mapped]"
        logging.debug("jmx_m_bean=%s", jmx_m_bean)

        # Not sure about the file name
        node_class = survol_mbean.MakeUri(pid_int, cls_nam)
        grph.add((node_class, lib_common.MakeProp("Object name"),
                  lib_util.NodeLiteral(obj_nam)))

        dict_m_bean_info = jmx_m_bean["info"]
        for keyInfo in dict_m_bean_info:
            val_info = dict_m_bean_info[keyInfo]
            grph.add((node_class, lib_common.MakeProp(keyInfo),
                      lib_util.NodeLiteral(val_info)))

        grph.add((node_class, lib_common.MakeProp("Attributes"),
                  lib_util.NodeLiteral(jmx_m_bean["attrs"])))

        grph.add((node_process, prop_m_bean, node_class))

    cgiEnv.OutCgiRdf()
示例#29
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()
    pid_int = int(cgiEnv.GetId())

    grph = cgiEnv.GetGraph()

    node_process = lib_uris.gUriGen.PidUri(pid_int)

    jmx_data = survol_java.GetJavaDataFromJmx(pid_int)
    try:
        jmx_data_m_beans = jmx_data["allMBeans"]
    except KeyError:
        jmx_data_m_beans = []

    prop_m_bean = lib_common.MakeProp("MBean")

    for jmx_m_bean in jmx_data_m_beans:
        cls_nam = jmx_m_bean["className"]
        obj_nam = jmx_m_bean["objectName"]

        # "=sun.management.ManagementFactoryHelper$1[java.nio:type=BufferPool,name=mapped]"
        logging.debug("jmx_m_bean=%s", jmx_m_bean)

        # Not sure about the file name
        node_class = survol_mbean.MakeUri(pid_int, obj_nam)
        grph.add((node_class, lib_common.MakeProp("Class name"),
                  lib_util.NodeLiteral(cls_nam)))

        grph.add((node_process, prop_m_bean, node_class))

    cgiEnv.OutCgiRdf("LAYOUT_RECT", [prop_m_bean])
示例#30
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()
    try:
        the_pid = int(cgiEnv.GetId())
    except Exception:
        lib_common.ErrorMessageHtml("Must provide a pid")

    grph = cgiEnv.GetGraph()

    node_process = lib_uris.gUriGen.PidUri(the_pid)
    CIM_Process.AddInfo(grph, node_process, [str(the_pid)])

    fil_cgroups = "/proc/%d/cgroup" % the_pid

    for lin_cg in open(fil_cgroups):
        split_cg = lin_cg.split(':')
        hierarchy = split_cg[0]
        subsys_name_list = split_cg[1]
        mount_path = split_cg[2]
        mount_path = mount_path[:-1]  # Strip trailing backslash-N
        mount_path_node = lib_uris.gUriGen.DirectoryUri(mount_path)

        for subsys_name in subsys_name_list.split(","):
            if subsys_name:
                cgrp_node = survol_cgroup.MakeUri(subsys_name)
                grph.add(
                    (node_process, lib_common.MakeProp("CGroup"), cgrp_node))
                grph.add((cgrp_node, lib_common.MakeProp("Hierarchy"),
                          lib_util.NodeLiteral(hierarchy)))
                grph.add((cgrp_node, lib_common.MakeProp("Control group path"),
                          mount_path_node))

    cgiEnv.OutCgiRdf()