Esempio n. 1
0
def Main():
    cgiEnv = lib_oracle.OracleEnv()

    grph = cgiEnv.GetGraph()

    #v$process
    #PID	NUMBER	Oracle process identifier
    #SPID	VARCHAR2(12)	Operating system process identifier
    #USERNAME	VARCHAR2(15)	Operating system process username. Any two-task user coming across the network has "-T" appended to the username.
    #TERMINAL	VARCHAR2(30)	Operating system terminal identifier
    #PROGRAM	VARCHAR2(48)	Program in progress
    #
    #v$session
    #SID	NUMBER	Session identifier
    #USER#	NUMBER	Oracle user identifier
    #USERNAME	VARCHAR2(30)	Oracle username
    #COMMAND	NUMBER	Command in progress (last statement parsed); for a list of values, see Table 7-5. These values also appear in the AUDIT_ACTIONS table.
    #SCHEMA#	NUMBER	Schema user identifier
    #SCHEMANAME	VARCHAR2(30)	Schema user name
    #OSUSER	VARCHAR2(30)	Operating system client user name
    #PROCESS	VARCHAR2(12)	Operating system client process ID
    #MACHINE	VARCHAR2(64)	Operating system machine name
    #TERMINAL	VARCHAR2(30)	Operating system terminal name
    #PROGRAM	VARCHAR2(48)	Operating system program name

    sql_query = """
	SELECT distinct sess.sid, sess.username, sess.schemaname, proc.spid,pid,sess.osuser,sess.machine,sess.process,
	sess.port,proc.terminal,sess.program,proc.tracefile
	  FROM v$session sess,
		   v$process proc
	 WHERE sess.type     = 'USER'
	   and sess.paddr = proc.addr
	"""

    node_oradb = oracle_db.MakeUri(cgiEnv.m_oraDatabase)

    try:
        result = lib_oracle.ExecuteQueryThrow(cgiEnv.ConnectStr(), sql_query)
    except:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("ExecuteQuery exception:%s in %s" %
                                    (str(exc), sql_query))

    for row in result:
        if row[0] == None:
            continue
        # print("\nUser="******"WORKGROUP\RCHATEAU-HP"
        user_machine = lib_oracle.OraMachineToIp(row[6])
        theMachineBox = lib_common.MachineBox(user_machine)

        # Process and Thread id of the CLIENT program, executing sqlplus.exe for example.
        sessPidTid = row[7]  # 7120:4784
        sessPid = sessPidTid.split(":")[0]
        procTerminal = row[9]
        sessProgram = row[10]

        nodeSession = oracle_session.MakeUri(cgiEnv.m_oraDatabase, str(row[0]))
        grph.add((nodeSession, lib_common.MakeProp("Oracle user"),
                  lib_common.NodeLiteral(oraUsername)))
        grph.add((nodeSession, lib_common.MakeProp("Schema"),
                  lib_common.NodeLiteral(schemaName)))
        grph.add((nodeSession, lib_common.MakeProp("Program"),
                  lib_common.NodeLiteral(sessProgram)))

        if schemaName != None:
            nodeSchema = oracle_schema.MakeUri(cgiEnv.m_oraDatabase,
                                               str(schemaName))
            grph.add((nodeSession, pc.property_oracle_schema, nodeSchema))
            grph.add((node_oradb, pc.property_oracle_db, nodeSchema))

        sys.stderr.write("user_proc_id=%s user_machine=%s\n" %
                         (user_proc_id, user_machine))
        # node_process = lib_common.RemoteBox(user_machine).PidUri( sessPid )
        node_process = theMachineBox.PidUri(sessPid)
        grph.add((node_process, lib_common.MakeProp("SystemPid"),
                  lib_common.NodeLiteral(user_proc_id)))
        grph.add((node_process, lib_common.MakeProp("OraclePid"),
                  lib_common.NodeLiteral(process_pid)))
        grph.add((node_process, lib_common.MakeProp("Terminal"),
                  lib_common.NodeLiteral(procTerminal)))
        grph.add((nodeSession, pc.property_oracle_session, node_process))

        if sessOsuser != None:
            sys.stderr.write("user_machine=%s sessOsuser=%s\n" %
                             (user_machine, sessOsuser))
            nodeOsUser = theMachineBox.UserUri(sessOsuser)
            grph.add((nodeOsUser, lib_common.MakeProp("OsUser"),
                      lib_common.NodeLiteral(sessOsuser)))
            grph.add((node_process, pc.property_user, nodeOsUser))

    cgiEnv.OutCgiRdf()
Esempio n. 2
0
def Main():

    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)

    entity_id = cgiEnv.GetId()
    logging.debug("entity_id=%s", entity_id)
    if entity_id == "":
        lib_common.ErrorMessageHtml("No entity_id")

    # Just the path, shorter than cgiEnv.get_parameters("xid")
    cimom_url = cgiEnv.GetHost()

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

    if name_space == "":
        name_space = "root/cimv2"
        logging.info("Setting namespace to default value.")

    if class_name == "":
        lib_common.ErrorMessageHtml("No class name. entity_id=%s" % entity_id)

    grph = cgiEnv.GetGraph()

    try:
        conn = lib_wbem.WbemConnection(cimom_url)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Connecting to :" + cimom_url +
                                    " Caught:" + str(exc))

    root_node = lib_util.EntityClassNode(class_name, name_space, cimom_url,
                                         "WBEM")
    kla_descrip = lib_wbem.WbemClassDescription(conn, class_name, name_space)
    if not kla_descrip:
        kla_descrip = "Undefined class %s %s" % (name_space, class_name)
    grph.add((root_node, pc.property_information,
              lib_util.NodeLiteral(kla_descrip)))

    split_monik = cgiEnv.m_entity_id_dict

    logging.debug("entity_wbem.py name_space=%s class_name=%s cimom_url=%s",
                  name_space, class_name, cimom_url)

    # This works:
    # conn = pywbem.WBEMConnection("http://192.168.0.17:5988",("pegasus","toto"))
    # conn.ExecQuery("WQL","select * from CIM_System","root/cimv2")
    # conn.ExecQuery("WQL",'select * from CIM_Process  where Handle="4125"',"root/cimv2")
    #
    # select * from CIM_Directory or CIM_DataFile does not return anything.

    inst_lists = WbemPlainExecQuery(conn, class_name, split_monik, name_space)
    logging.debug("inst_lists=%s", str(inst_lists))
    if inst_lists is None:
        inst_lists = WbemNoQueryOneInst(conn, class_name, split_monik,
                                        name_space)
        if inst_lists is None:
            inst_lists = WbemNoQueryFilterInstances(conn, class_name,
                                                    split_monik, name_space)

    # TODO: Some objects are duplicated.
    # 'CSCreationClassName'   CIM_UnitaryComputerSystem Linux_ComputerSystem
    # 'CreationClassName'     PG_UnixProcess            TUT_UnixProcess
    num_insts = len(inst_lists)

    # If there are duplicates, adds a property which we hope is different.
    prop_discrim = "CreationClassName"

    # TODO!! WHAT OF THIS IS NOT THE RIGHT ORDER ???
    # Remove the double-quotes around the argument. WHAT IF THEY ARE NOT THERE ??

    for an_inst in inst_lists:

        # TODO: Use the right accessor for better performance.
        # On peut peut etre mettre tout ca dans une fonction sauf l execution de la query.
        dict_inst = dict(an_inst)

        # This differentiates several instance with the same properties.
        if num_insts > 1:
            # TODO: Should check if this property is different for all instances !!!
            with_extra_args = {prop_discrim: dict_inst[prop_discrim]}
            all_args = split_monik.copy()
            all_args.update(with_extra_args)
            dict_props = all_args
        else:
            dict_props = split_monik

        host_only = lib_util.EntHostToIp(cimom_url)
        uri_inst = lib_common.MachineBox(host_only).node_from_dict(
            class_name, dict_props)

        grph.add((root_node, lib_common.MakeProp(class_name), uri_inst))

        AddNamespaceLink(grph, root_node, name_space, cimom_url, class_name)

        # None properties are not printed.
        for iname_key in dict_inst:
            # Do not print twice values which are in the name.
            if iname_key in split_monik:
                continue
            iname_val = dict_inst[iname_key]
            # TODO: If this is a reference, create a Node !!!!!!!
            if not iname_val is None:
                grph.add((uri_inst, lib_common.MakeProp(iname_key),
                          lib_util.NodeLiteral(iname_val)))

        # TODO: Should call Associators(). Same for References().

    cgiEnv.OutCgiRdf()
def Main():
    # TODO: The type should really be an integer.
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)

    # http://192.168.1.88
    machine_name = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    cimom_url = lib_wbem.HostnameToWbemServer(machine_name)

    logging.debug("machine_name=%s cimom_url=%s", machine_name, cimom_url)

    # If running on the local machine, pass the host as None otherwise authorization is checked
    # just like a remote machine, which means User Account Control (UAC) disabling,
    # and maybe setting LocalAccountTokenFilterPolicy=1
    server_box = lib_common.MachineBox(machine_name)

    # >>> conn = pywbem.WBEMConnection("http://192.168.1.88:5988" , ('pe***us','t*t*') )
    try:
        conn_wbem = lib_wbem.WbemConnection(cimom_url)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Connecting to :" + cimom_url +
                                    " Caught:" + str(exc))

    try:
        lst_proc = conn_wbem.EnumerateInstances(ClassName="PG_UnixProcess",
                                                namespace="root/cimv2")
    except Exception as exc:
        lib_common.ErrorMessageHtml("Error:" + str(exc))

    # We should be using the class CMI_Process instead of PG_UnixProcess but it returns the error:
    # Python 2.7, pywbem.__version__ '0.8.0-dev'
    # >>> conn = pywbem.WBEMConnection("https://192.168.1.88:5989" , ('my-user','my-pass') )
    # >>> lst = conn.EnumerateInstanceNames(ClassName="CIM_Process",namespace="root/cimv2")
    # ...pywbem.cim_operations.CIMError: (1, u'CIM_ERR_FAILED: Error initializing CMPI MI /home/jsmith/TestProviderOpenLMI/tutorial_final/T
    # UT_UnixProcess.py, the following MI factory function(s) returned an error: _Generic_Create_InstanceMI, message was: cmpi:Traceback (
    # most recent call last):<br>  File "/usr/lib64/python2.7/site-packages/cmpi_pywbem_bindings.py", line 34, in <module><br>    from pyw
    # bem.cim_provider2 import ProviderProxy<br>ImportError: No module named cim_provider2<br>')

    # >>> lst_proc[3].keys()
    # [u'OSCreationClassName', u'UserModeTime', u'Parameters', u'ExecutionState', u'ProcessGroupID', u'Priority', u'OtherExecutionDescript
    # ion', u'Handle', u'Description', u'RealUserID', u'CSCreationClassName', u'ProcessTTY', u'OSName', u'ProcessSessionID', u'CreationCla
    # ssName', u'WorkingSetSize', u'Name', u'CSName', u'ParentProcessID', u'KernelModeTime', u'Caption', u'ProcessNiceValue']

    # With a dictionary, so the nodes are created once only.
    Main.dictWbemPidToNode = {}

    def wbem_pid_to_node(proc_id):
        logging.debug("procId=%s", proc_id)
        try:
            return Main.dictWbemPidToNode[proc_id]
        except KeyError:
            node = server_box.PidUri(proc_id)

            Main.dictWbemPidToNode[proc_id] = node
            return node

    for one_proc in lst_proc:
        node_process = wbem_pid_to_node(one_proc["Handle"])
        parent_node_process = wbem_pid_to_node(one_proc["ParentProcessID"])

        grph.add((node_process, pc.property_ppid, parent_node_process))

        grph.add((node_process, pc.property_information,
                  lib_util.NodeLiteral(one_proc["Caption"])))

        if False:
            if one_proc["Caption"] != one_proc["Description"]:
                grph.add((node_process, lib_common.MakeProp("Description"),
                          lib_util.NodeLiteral(one_proc["Description"])))

            for prpNam in [
                    "WorkingSetSize", "KernelModeTime", "ProcessNiceValue",
                    "OtherExecutionDescription"
            ]:
                try:
                    grph.add((node_process, lib_common.MakeProp(prpNam),
                              lib_util.NodeLiteral(one_proc["prpNam"])))
                except KeyError:
                    pass

    cgiEnv.OutCgiRdf()
Esempio n. 4
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)
    pid = int(cgiEnv.GetId())
    machine_name = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    server_box = lib_common.MachineBox(machine_name)

    node_process = server_box.PidUri(pid)

    cnnct = lib_wmi.WmiConnect(machine_name, "/root/cimv2")

    # This also works when selecting from class Win32_Process.
    lstProcs = cnnct.CIM_Process(Handle=pid)

    # instance of Win32_Process
    # {
    #         Caption = "sqlwriter.exe";
    #         CreationClassName = "Win32_Process";
    #         CreationDate = "20161215105057.836987+000";
    #         CSCreationClassName = "Win32_ComputerSystem";
    #         CSName = "TITI";
    #         Description = "sqlwriter.exe";
    #         Handle = "1908";
    #         HandleCount = 101;
    #         KernelModeTime = "625000";
    #         Name = "sqlwriter.exe";
    #         OSCreationClassName = "Win32_OperatingSystem";
    #         OSName = "Microsoft Windows 8.1|C:\\Windows|\\Device\\Harddisk0\\Partition4";
    #         OtherOperationCount = "151";
    #         OtherTransferCount = "1316";
    #         PageFaults = 3735;
    #         PageFileUsage = 1508;
    #         ParentProcessId = 624;
    #         PeakPageFileUsage = 1860;
    #         PeakVirtualSize = "47603712";
    #         PeakWorkingSetSize = 5796;
    #         Priority = 8;
    #         PrivatePageCount = "1544192";
    #         ProcessId = 1908;
    #         QuotaNonPagedPoolUsage = 9;
    #         QuotaPagedPoolUsage = 72;
    #         QuotaPeakNonPagedPoolUsage = 10;
    #         QuotaPeakPagedPoolUsage = 72;
    #         ReadOperationCount = "0";
    #         ReadTransferCount = "0";
    #         SessionId = 0;
    #         ThreadCount = 2;
    #         UserModeTime = "625000";
    #         VirtualSize = "39182336";
    #         WindowsVersion = "6.3.9600";
    #         WorkingSetSize = "4780032";
    #         WriteOperationCount = "0";
    #         WriteTransferCount = "0";
    # };

    # In some circumstances - when the process is local ? - it can display the extra properties:

    #        CommandLine = "\"C:\\Windows\\system32\\SearchFilterHost
    #        ExecutablePath = "C:\\Windows\\system32\\SearchFilterHos

    lst_prop_names = [
        "CreationDate", "CSName", "HandleCount", "KernelModeTime", "Name",
        "OSName", "OtherOperationCount", "OtherTransferCount", "PageFaults",
        "PageFileUsage", "PeakPageFileUsage", "PeakVirtualSize",
        "PeakWorkingSetSize", "Priority", "PrivatePageCount",
        "QuotaNonPagedPoolUsage", "QuotaPagedPoolUsage",
        "QuotaPeakNonPagedPoolUsage", "QuotaPeakPagedPoolUsage",
        "ReadOperationCount", "ReadTransferCount", "SessionId", "ThreadCount",
        "UserModeTime", "VirtualSize", "WorkingSetSize", "WriteOperationCount",
        "WriteTransferCount"
    ]

    class_name = "CIM_Process"

    map_prop_units = lib_wmi.WmiDictPropertiesUnit(cnnct, class_name)

    # There should be one process only.
    for wmi_proc in lstProcs:
        grph.add((node_process, pc.property_information,
                  lib_util.NodeLiteral(wmi_proc.Description)))

        for prp_proc in lst_prop_names:
            val_proc = getattr(wmi_proc, prp_proc)
            try:
                val_unit = map_prop_units[prp_proc]
            except KeyError:
                val_unit = ""
            val_proc_unit = lib_util.AddSIUnit(val_proc, val_unit)
            grph.add((node_process, lib_common.MakeProp(prp_proc),
                      lib_util.NodeLiteral(val_proc_unit)))

        parent_node_process = server_box.PidUri(wmi_proc.ParentProcessId)
        grph.add((node_process, pc.property_ppid, parent_node_process))

    cgiEnv.OutCgiRdf()
Esempio n. 5
0
def Main():
    """
    This is similar to the script displaying shares for a given SMB server.
    Maybe in the future it will have to be different.
    """
    cgiEnv = lib_common.ScriptEnvironment()
    host_name = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    node_smb_shr = lib_uris.gUriGen.SmbServerUri(host_name)

    smbclient_cmd = ["smbclient", "-L", host_name, "-N"]

    try:
        smbclient_pipe = lib_common.SubProcPOpen(smbclient_cmd)
    except Exception:
        lib_common.ErrorMessageHtml("Cannot run command:" +
                                    " ".join(smbclient_cmd))

    smbclient_last_output, smbclient_err = smbclient_pipe.communicate()

    lines = smbclient_last_output.split('\n')

    mode_shared_list = False
    for lin in lines:
        # print( "l="+lin+"<br>" )
        # Normally this is only the first line
        # session setup failed: NT_STATUS_LOGON_FAILURE
        mtch_net = re.match(r"^.*(NT_STATUS_.*)", lin)
        if mtch_net:
            lib_common.ErrorMessageHtml("Smb failure: " + mtch_net.group(1) +
                                        " to smb share:" + node_smb_shr)

        if re.match(r"^\sServer\s+Comment", lin):
            mode_shared_list = False
            continue

        if re.match(r"^\sWorkgroup\s+Master", lin):
            mode_shared_list = False
            continue

        if re.match(r"^\sSharename\s+Type\s+Comment", lin):
            mode_shared_list = True
            continue

        if re.match(r"^\s*----+ +---+ +", lin):
            continue

        if mode_shared_list:
            # The type can be "Disk", "Printer" or "IPC".
            mtch_share = re.match(r"^\s+([^\s]+)\s+Disk\s+(.*)$", lin)
            if mtch_share:
                share_name = mtch_share.group(1)

                share_node = lib_common.MachineBox(host_name).SmbShareUri(
                    share_name)

                grph.add((node_smb_shr, pc.property_smbshare, share_node))

    cgiEnv.OutCgiRdf()