Esempio n. 1
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
Esempio n. 2
0
def Main():
	cgiEnv = lib_common.CgiEnv()

	grph = cgiEnv.GetGraph()

	dsnNam = survol_odbc_dsn.GetDsnNameFromCgi(cgiEnv)

	DEBUG("dsn=(%s)", dsnNam)

	nodeDsn = survol_sqlserver_dsn.MakeUri(dsnNam)

	ODBC_ConnectString = survol_odbc_dsn.MakeOdbcConnectionString(dsnNam)
	try:
		cnxn = pyodbc.connect(ODBC_ConnectString)
		DEBUG("Connected: %s", dsnNam)
		cursorSessions = cnxn.cursor()

		qrySessions = """
		SELECT host_name,host_process_id,session_id,program_name,client_interface_name,original_login_name,nt_domain,nt_user_name
		FROM sys.dm_exec_sessions
		"""

		propSqlServerSession = lib_common.MakeProp("SqlServer session")
		propSqlServerHostProcess = lib_common.MakeProp("Host process")
		propSqlServerProgramName = lib_common.MakeProp("Program name")
		propSqlServerClientInterface = lib_common.MakeProp("Client Interface")

		propSqlServerOriginalLoginName = lib_common.MakeProp("original_login_name")
		propSqlServerNTDomain = lib_common.MakeProp("nt_domain")
		propSqlServerNTUserName = lib_common.MakeProp("nt_user_name")

		for rowSess in cursorSessions.execute(qrySessions):
			DEBUG("rowSess.session_id=(%s)", rowSess.session_id)
			nodeSession = session.MakeUri(dsnNam, rowSess.session_id)
			grph.add((nodeDsn, propSqlServerSession, nodeSession))

			if rowSess.host_process_id:
				node_process = lib_common.RemoteBox(rowSess.host_name).PidUri(rowSess.host_process_id)
				grph.add((node_process, pc.property_pid, lib_common.NodeLiteral(rowSess.host_process_id)))
				grph.add((nodeSession, propSqlServerHostProcess, node_process))

			if rowSess.program_name:
				grph.add((nodeSession, propSqlServerProgramName, lib_common.NodeLiteral(rowSess.program_name)))
			if rowSess.client_interface_name:
				grph.add((nodeSession, propSqlServerClientInterface, lib_common.NodeLiteral(rowSess.client_interface_name)))

			# TODO: Make nodes with these:
			if rowSess.original_login_name:
				grph.add((nodeSession, propSqlServerOriginalLoginName, lib_common.NodeLiteral(rowSess.original_login_name)))
			if rowSess.nt_domain:
				grph.add((nodeSession, propSqlServerNTDomain, lib_common.NodeLiteral(rowSess.nt_domain)))
			if rowSess.nt_user_name:
				grph.add((nodeSession, propSqlServerNTUserName, lib_common.NodeLiteral(rowSess.nt_user_name)))

	except Exception:
		exc = sys.exc_info()[0]
		lib_common.ErrorMessageHtml(
			"nodeDsn=%s Unexpected error:%s" % (dsnNam, str(sys.exc_info())))  # cgiEnv.OutCgiRdf()

	cgiEnv.OutCgiRdf("LAYOUT_RECT",[propSqlServerSession,propSqlServerHostProcess])
Esempio n. 3
0
def Main():
    # TODO: can_process_remote should be suppressed because it duplicates CanProcessRemote
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)
    pid = int(cgiEnv.GetId())
    machine_name = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    cimom_url = lib_wbem.HostnameToWbemServer(machine_name)

    DEBUG(
        "wbem_process_info.py currentHostname=%s pid=%d machine_name=%s cimom_url=%s",
        lib_util.currentHostname, pid, machine_name, cimom_url)

    conn_wbem = lib_wbem.WbemConnection(cimom_url)

    name_space = "root/cimv2"
    try:
        inst_lists = conn_wbem.ExecQuery(
            "WQL", 'select * from CIM_Process  where Handle="%s"' % pid,
            name_space)
    except:
        lib_common.ErrorMessageHtml("Error:" + str(sys.exc_info()))

    class_name = "CIM_Process"
    dict_props = {"Handle": pid}

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

    # There should be only one object, hopefully.
    for an_inst in inst_lists:
        dict_inst = dict(an_inst)

        host_only = lib_util.EntHostToIp(cimom_url)
        if lib_util.IsLocalAddress(host_only):
            uri_inst = lib_common.gUriGen.UriMakeFromDict(
                class_name, dict_props)
        else:
            uri_inst = lib_common.RemoteBox(host_only).UriMakeFromDict(
                class_name, dict_props)

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

        url_namespace = lib_wbem.NamespaceUrl(name_space, cimom_url,
                                              class_name)
        nod_namespace = lib_common.NodeUrl(url_namespace)
        grph.add((root_node, pc.property_cim_subnamespace, nod_namespace))

        # None properties are not printed.
        for iname_key in dict_inst:
            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_common.NodeLiteral(iname_val)))

        # TODO: Call the method Associators(). Idem References().

    cgiEnv.OutCgiRdf()
Esempio n. 4
0
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)

    try:
        # Exception if local machine.
        hostName = cgiEnv.m_entity_id_dict["Domain"]
    except KeyError:
        hostName = None

    if not hostName or lib_util.IsLocalAddress(hostName):
        serverBox = lib_common.gUriGen
        serverNode = lib_common.nodeMachine
        servName_or_None = None
    else:
        serverBox = lib_common.RemoteBox(hostName)
        serverNode = lib_common.gUriGen.HostnameUri(hostName)
        servName_or_None = hostName

        # hostname = "Titi" for example
        try:
            lib_win32.WNetAddConnect(hostName)
        except:
            lib_common.ErrorMessageHtml("Error WNetAddConnect %s:%s" %
                                        (hostName, str(sys.exc_info())))

    userName = cgiEnv.m_entity_id_dict["Name"]

    DEBUG("hostName=%s userName=%s", hostName, userName)

    grph = cgiEnv.GetGraph()

    nodeUser = survol_Win32_UserAccount.MakeUri(userName, hostName)

    # TODO: Quid de NetUserGetGroups ??

    # [(groupName, attribute), ...] = NetUserGetGroups(serverName, userName )
    try:
        resuList = win32net.NetUserGetLocalGroups(servName_or_None, userName)
    except:
        lib_common.ErrorMessageHtml("Error:userName="******":servName_or_None=" +
                                    str(servName_or_None) + ":" +
                                    str(sys.exc_info()))

    for groupName in resuList:
        nodeGroup = survol_Win32_Group.MakeUri(groupName, hostName)
        grph.add((nodeUser, pc.property_group, nodeGroup))

        if hostName:
            nodeGroupRemote = serverBox.UriMakeFromDict(
                "Win32_Group", {
                    "Name": groupName,
                    "Domain": hostName
                })
            # TODO: Instead, both object must have the same universal alias
            grph.add((nodeGroup, pc.property_alias, nodeGroupRemote))

    cgiEnv.OutCgiRdf()
Esempio n. 5
0
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    dsnNam = survol_odbc_dsn.GetDsnNameFromCgi(cgiEnv)

    sys.stderr.write("dsn=(%s)\n" % dsnNam)

    nodeDsn = survol_sqlserver_dsn.MakeUri(dsnNam)

    ODBC_ConnectString = survol_odbc_dsn.MakeOdbcConnectionString(dsnNam)
    try:
        cnxn = pyodbc.connect(ODBC_ConnectString)
        sys.stderr.write("Connected: %s\n" % dsnNam)
        cursorQueries = cnxn.cursor()

        qryQueries = """
			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
		"""

        propSqlServerSqlQuery = lib_common.MakeProp("Sql query")
        propSqlServerHostProcess = lib_common.MakeProp("Host process")
        propSqlServerStatus = lib_common.MakeProp("Status")

        for rowQry in cursorQueries.execute(qryQueries):
            sys.stderr.write("rowQry.session_id=(%s)\n" % rowQry.session_id)
            nodeSession = session.MakeUri(dsnNam, rowQry.session_id)

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

            # TODO: Must add connection information so we can go from the tables to sqlserver itself.
            nodeSqlQuery = sql_query.MakeUri(queryClean, dsnNam)
            grph.add((nodeSession, propSqlServerSqlQuery, nodeSqlQuery))
            node_process = lib_common.RemoteBox(rowQry.host_name).PidUri(
                rowQry.host_process_id)
            grph.add((node_process, pc.property_pid,
                      lib_common.NodeLiteral(rowQry.host_process_id)))

            grph.add((nodeSession, propSqlServerHostProcess, node_process))
            grph.add((nodeSession, propSqlServerStatus,
                      lib_common.NodeLiteral(rowQry.status)))

    except Exception:
        exc = sys.exc_info()[0]
        lib_common.ErrorMessageHtml("nodeDsn=%s Unexpected error:%s" %
                                    (dsnNam, str(sys.exc_info())))

    cgiEnv.OutCgiRdf()
Esempio n. 6
0
def Main():
    cgiEnv = lib_oracle.OracleEnv()
    oraSession = cgiEnv.m_entity_id_dict["Session"]
    grph = cgiEnv.GetGraph()
    node_oraSession = oracle_session.MakeUri(cgiEnv.m_oraDatabase, oraSession)

    # TYPE = "VIEW", "TABLE", "PACKAGE BODY"
    sql_query = "select SID,STATUS,USERNAME,SERVER,SCHEMANAME,COMMAND,MACHINE,PORT,OSUSER,PROCESS,SERVICE_NAME,ACTION from V$SESSION where SID='%s'" % oraSession
    sys.stderr.write("sql_query=%s\n" % sql_query)
    result = lib_oracle.ExecuteQuery(cgiEnv.ConnectStr(), sql_query)

    # There should be only one.
    for row in result:
        sys.stderr.write("SID=%s\n" % row[0])

        grph.add((node_oraSession, lib_common.MakeProp("Status"),
                  lib_common.NodeLiteral(row[1])))
        grph.add((node_oraSession, lib_common.MakeProp("Username"),
                  lib_common.NodeLiteral(row[2])))
        grph.add((node_oraSession, lib_common.MakeProp("Server"),
                  lib_common.NodeLiteral(row[3])))

        # grph.add( ( node_oraSession, lib_common.MakeProp("Schema"), lib_common.NodeLiteral(row[4]) ) )
        nodeSchema = oracle_schema.MakeUri(cgiEnv.m_oraDatabase, str(row[4]))
        grph.add((node_oraSession, pc.property_oracle_schema, nodeSchema))

        grph.add((node_oraSession, lib_common.MakeProp("Command"),
                  lib_common.NodeLiteral(row[5])))

        # This returns an IP address from "WORKGROUP\RCHATEAU-HP"
        user_machine = lib_oracle.OraMachineToIp(row[6])
        nodeMachine = lib_common.gUriGen.HostnameUri(user_machine)
        grph.add((nodeMachine, pc.property_information,
                  lib_common.NodeLiteral(row[6])))

        grph.add((node_oraSession, lib_common.MakeProp("Port"),
                  lib_common.NodeLiteral(row[7])))
        grph.add((node_oraSession, lib_common.MakeProp("OsUser"),
                  lib_common.NodeLiteral(row[8])))
        # grph.add( ( node_oraSession, lib_common.MakeProp("Process"), lib_common.NodeLiteral(row[9]) ) )
        sessPidTid = row[9]  # 7120:4784
        sessPid = sessPidTid.split(":")[0]
        node_process = lib_common.RemoteBox(user_machine).PidUri(sessPid)
        grph.add((node_process, lib_common.MakeProp("Pid"),
                  lib_common.NodeLiteral(sessPid)))
        grph.add((node_oraSession, pc.property_oracle_session, node_process))

        grph.add(
            (node_oraSession, lib_common.MakeProp("Hostname"), nodeMachine))

        grph.add((node_oraSession, lib_common.MakeProp("ServiceName"),
                  lib_common.NodeLiteral(row[10])))
        grph.add((node_oraSession, lib_common.MakeProp("Action"),
                  lib_common.NodeLiteral(row[11])))

    cgiEnv.OutCgiRdf("LAYOUT_RECT")
Esempio n. 7
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()
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_sqlserver_dsn.MakeUri(dsn_nam)

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

        qry_sessions = """
        SELECT host_name,host_process_id,session_id,program_name,client_interface_name,original_login_name,nt_domain,nt_user_name
        FROM sys.dm_exec_sessions where host_process_id is not null
        """

        prop_sql_server_session = lib_common.MakeProp("SqlServer session")
        prop_sql_server_host_process = lib_common.MakeProp("Host process")
        prop_sql_server_program_name = lib_common.MakeProp("Program name")
        prop_sql_server_client_interface = lib_common.MakeProp("Client Interface")

        prop_sql_server_original_login_name = lib_common.MakeProp("original_login_name")
        prop_sql_server_nt_domain = lib_common.MakeProp("nt_domain")
        prop_sql_server_nt_user_name = lib_common.MakeProp("nt_user_name")

        for row_sess in cursor_sessions.execute(qry_sessions):
            logging.debug("row_sess.session_id=(%s)", row_sess.session_id)
            node_session = session.MakeUri(dsn_nam, row_sess.session_id)
            grph.add((node_dsn, prop_sql_server_session, node_session))

            node_process = lib_common.RemoteBox(row_sess.host_name).PidUri(row_sess.host_process_id)
            grph.add((node_process, pc.property_pid, lib_util.NodeLiteral(row_sess.host_process_id)))

            grph.add((node_session, prop_sql_server_host_process, node_process))
            grph.add((node_session, prop_sql_server_program_name, lib_util.NodeLiteral(row_sess.program_name)))
            grph.add((node_session, prop_sql_server_client_interface, lib_util.NodeLiteral(row_sess.client_interface_name)))

            # TODO: Make nodes with these:

            grph.add(
                (node_session, prop_sql_server_original_login_name, lib_util.NodeLiteral(row_sess.original_login_name)))
            grph.add((node_session, prop_sql_server_nt_domain, lib_util.NodeLiteral(row_sess.nt_domain)))
            grph.add((node_session, prop_sql_server_nt_user_name, lib_util.NodeLiteral(row_sess.nt_user_name)))

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

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

    try:
        # Exception if local machine.
        host_name = cgiEnv.m_entity_id_dict["Domain"]
    except KeyError:
        host_name = None

    if lib_util.is_local_address(host_name):
        server_box = lib_uris.gUriGen
        serv_name_or_none = None
    else:
        server_box = lib_common.RemoteBox(host_name)
        serv_name_or_none = host_name

        try:
            lib_win32.WNetAddConnect(host_name)
        except Exception as exc:
            lib_common.ErrorMessageHtml("Error WNetAddConnect %s:%s" %
                                        (host_name, str(exc)))

    user_name = cgiEnv.m_entity_id_dict["Name"]

    logging.debug("host_name=%s user_name=%s", host_name, user_name)

    grph = cgiEnv.GetGraph()

    node_user = survol_Win32_UserAccount.MakeUri(user_name, host_name)

    # TODO: And NetUserGetGroups ??

    # [(group_name, attribute), ...] = NetUserGetGroups(serverName, user_name )
    try:
        resu_list = win32net.NetUserGetLocalGroups(serv_name_or_none,
                                                   user_name)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Error:user_name=" + user_name +
                                    ":serv_name_or_none=" +
                                    str(serv_name_or_none) + ":" + str(exc))

    for group_name in resu_list:
        node_group = survol_Win32_Group.MakeUri(group_name, host_name)
        grph.add((node_user, pc.property_group, node_group))

        if host_name:
            node_group_remote = server_box.node_from_dict(
                "Win32_Group", {
                    "Name": group_name,
                    "Domain": host_name
                })
            # TODO: Instead, both object must have the same universal alias
            grph.add((node_group, pc.property_alias, node_group_remote))

    cgiEnv.OutCgiRdf()
Esempio n. 10
0
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)

    try:
        # Exception if local machine.
        hostName = cgiEnv.m_entity_id_dict["Domain"]
    except KeyError:
        hostName = None

    if not hostName or lib_util.IsLocalAddress(hostName):
        serverBox = lib_common.gUriGen
        serverNode = lib_common.nodeMachine
        servName_or_None = None
    else:
        serverBox = lib_common.RemoteBox(hostName)
        serverNode = lib_common.gUriGen.HostnameUri(hostName)
        servName_or_None = hostName

        # hostname = "Titi" for example
        # lib_win32.WNetAddConnect(hostName)

    userName = cgiEnv.m_entity_id_dict["Name"]

    grph = cgiEnv.GetGraph()

    nodeUser = survol_Win32_UserAccount.MakeUri(userName, hostName)

    try:
        infoList = win32net.NetUserGetInfo(servName_or_None, userName, 2)
    except:
        lib_common.ErrorMessageHtml("Error:" + str(sys.exc_info()))

    for infoKey in infoList:

        try:
            infoVal = infoList[infoKey]
            grph.add((nodeUser, lib_common.MakeProp(infoKey),
                      lib_common.NodeLiteral(infoVal)))
        except:
            txtDisp = str(sys.exc_info()[1])
            grph.add((nodeUser, lib_common.MakeProp(infoKey),
                      lib_common.NodeLiteral(txtDisp)))

    cgiEnv.OutCgiRdf()
Esempio n. 11
0
def AddMimeUrl(grph, filNode, entity_type, mime_type, entity_id_arr):
    entity_host = None
    if entity_host:
        genObj = lib_common.RemoteBox(entity_host)
    else:
        genObj = lib_common.gUriGen

    mimeNode = genObj.UriMakeFromScript('/entity_mime.py', entity_type,
                                        *entity_id_arr)

    # So that the MIME type is known without loading the URLs.
    # Also, it allows to force a specific MIME type.
    # The MIME type is not coded in the property because it is an attribute of the object.

    # mimeNodeWithMode =  lib_util.AnyUriModed(mimeNode, "mime/" + mime_type)
    # sys.stderr.write("lib_mime.AddMimeUrl BEFORE mimeNode=%s\n"%(mimeNode))
    mimeNodeWithMode = mimeNode + "&" + "mode=" + mimeModePrefix + mime_type

    grph.add((filNode, pc.property_rdf_data_nolist2,
              lib_common.NodeUrl(mimeNodeWithMode)))
Esempio n. 12
0
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)
    machineName = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    # 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
    if not machineName or lib_util.IsLocalAddress(machineName):
        machNameNotNone = lib_util.currentHostname
        serverBox = lib_common.gUriGen
    else:
        machNameNotNone = machineName
        serverBox = lib_common.RemoteBox(machineName)

    try:
        # On a le probleme "access denied" avec tous les acces remote windows.
        # Meme probleme aussi avec WMI alors que ca marchait avant.
        # Comme s'il y avait une connection implicite de rchateau, quand ca marchait, et qu'elle ait disparu maintenant.
        # Toutefois, ceci fonctionne.
        # >>> c = wmi.WMI(wmi=wmi.connect_server(server='Titi', namespace="/root/cimv2", user='******', password='******'))

        sys.stderr.write("Explicit WMI connection machineName=%s\n" %
                         (machNameNotNone))

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

        #(wmiUser,wmiPass) = lib_credentials.GetCredentials("WMI",machineName)
        #sys.stderr.write("machineName= %wmiUser=%s\n" % ( machineName, wmiUser ) )
        #cnnct = wmi.WMI(wmi=wmi.connect_server(server=machineName, namespace="/root/cimv2", user=wmiUser, password=wmiPass))
    except Exception:
        lib_common.ErrorMessageHtml("WMI " + machineName +
                                    " processes. Caught:" +
                                    str(sys.exc_info()))

    # With a dictionary so node are created once only.
    Main.dictPidToNode = {}

    def PidToNode(procId):
        try:
            return Main.dictPidToNode[procId]
        except KeyError:
            node = serverBox.PidUri(procId)

            Main.dictPidToNode[procId] = node
            return node

    for processProperties in cnnct.Win32_Process():

        node_process = PidToNode(processProperties.ProcessId)
        parent_node_process = PidToNode(processProperties.ParentProcessId)

        grph.add((node_process, pc.property_ppid, parent_node_process))
        #grph.add( ( node_process, pc.property_pid, lib_common.NodeLiteral(processProperties.ProcessId) ) )

        # Si on laisse faire le code, ca va afficher:
        # No such process:1292 at Titi
        # pid 1292
        #
        # Or, c'est idiot car on a deja toutes les donnees sous la main.

        # >>> lp = cnnct.Win32_Process ()
        # >>> lp[0]
        # <_wmi_object: \\TITI\root\cimv2:Win32_Process.Handle="0">
        # >>> str(lp[0])
        # '\ninstance of Win32_Process\n{\n\tCaption = "System Idle Process";\n\tCreationClassName = "Win32_Process";\n\tCreationDate = "20161
        # 215105022.381553+000";\n\tCSCreationClassName = "Win32_ComputerSystem";\n\tCSName = "TITI";\n\tDescription = "System Idle Process";\
        # n\tHandle = "0";\n\tHandleCount = 0;\n\tKernelModeTime = "23403826406250";\n\tName = "System Idle Process";\n\tOSCreationClassName =
        #  "Win32_OperatingSystem";\n\tOSName = "Microsoft Windows 8.1|C:\\\\Windows|\\\\Device\\\\Harddisk0\\\\Partition4";\n\tOtherOperation
        # Count = "0";\n\tOtherTransferCount = "0";\n\tPageFaults = 1;\n\tPageFileUsage = 0;\n\tParentProcessId = 0;\n\tPeakPageFileUsage = 0;
        # \n\tPeakVirtualSize = "65536";\n\tPeakWorkingSetSize = 4;\n\tPriority = 0;\n\tPrivatePageCount = "0";\n\tProcessId = 0;\n\tQuotaNonP
        # agedPoolUsage = 0;\n\tQuotaPagedPoolUsage = 0;\n\tQuotaPeakNonPagedPoolUsage = 0;\n\tQuotaPeakPagedPoolUsage = 0;\n\tReadOperationCo
        # unt = "0";\n\tReadTransferCount = "0";\n\tSessionId = 0;\n\tThreadCount = 4;\n\tUserModeTime = "0";\n\tVirtualSize = "65536";\n\tWin
        # dowsVersion = "6.3.9600";\n\tWorkingSetSize = "4096";\n\tWriteOperationCount = "0";\n\tWriteTransferCount = "0";\n};\n'

        grph.add((node_process, pc.property_information,
                  lib_common.NodeLiteral(processProperties.Caption)))
        if processProperties.Caption != processProperties.Description:
            grph.add((node_process, lib_common.MakeProp("Description"),
                      lib_common.NodeLiteral(processProperties.Description)))

        # AJOUTER LE LIEN WMI ICI ET DANS LA PAGE http://127.0.0.1:8000/survol/entity.py?xid=Titi@CIM_Process.Handle=6344

        # All the rest is not needed yet, there would be too much things to display.
        #grph.add( ( node_process, pc.property_command, lib_common.NodeLiteral(process.CommandLine) ) )
        #
        #exec_name = process.ExecutablePath
        #if exec_name != None:
        #	exec_node = lib_common.gUriGen.FileUri( exec_name.replace('\\','/') )
        #	grph.add( ( node_process, pc.property_runs, exec_node ) )

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

	cgiEnv = lib_common.CgiEnv(can_process_remote = True)

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


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

	nameSpace, className = cgiEnv.get_namespace_type()
	DEBUG("entity_wbem.py cimomUrl=%s nameSpace=%s className=%s", cimomUrl,nameSpace,className)

	if nameSpace == "":
		nameSpace = "root/cimv2"
		INFO("Setting namespace to default value\n")


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

	grph = cgiEnv.GetGraph()

	conn = lib_wbem.WbemConnection(cimomUrl)

	rootNode = lib_util.EntityClassNode( className, nameSpace, cimomUrl, "WBEM" )
	klaDescrip = lib_wbem.WbemClassDescription(conn,className,nameSpace)
	if not klaDescrip:
		klaDescrip = "Undefined class %s %s" % ( nameSpace, className )
	grph.add( ( rootNode, pc.property_information, lib_common.NodeLiteral(klaDescrip ) ) )

	splitMonik = lib_util.SplitMoniker( cgiEnv.m_entity_id )

	DEBUG("entity_wbem.py nameSpace=%s className=%s cimomUrl=%s",nameSpace,className,cimomUrl)

	# 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.


	instLists = WbemPlainExecQuery( conn, className, splitMonik, nameSpace )
	DEBUG("entity_wbem.py instLists=%s",str(instLists))
	if instLists is None:
		instLists = WbemNoQueryOneInst( conn, className, splitMonik, nameSpace )
		if instLists is None:
			instLists = WbemNoQueryFilterInstances( conn, className, splitMonik, nameSpace )

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

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

	# TODO!! WHAT OF THIS IS NOT THE RIGHT ORDER ???
	# Remove the double-quotes around the argument. WHAT IF THEY ARE NOT THERE ??
	# arrVals = [ ChopEnclosingParentheses( splitMonik[qryKey] ) for qryKey in splitMonik ]

	for anInst in instLists:

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

		# This differentiates several instance with the same properties.


		if numInsts > 1:
			# TODO: Should check if this property is different for all instances !!!
			withExtraArgs = { propDiscrim : dictInst[ propDiscrim ] }
			allArgs = splitMonik.copy()
			allArgs.update(withExtraArgs)
			dictProps = allArgs
		else:
			dictProps = splitMonik

		hostOnly = lib_util.EntHostToIp(cimomUrl)
		if lib_util.IsLocalAddress(hostOnly):
			uriInst = lib_common.gUriGen.UriMakeFromDict(className, dictProps)
		else:
			uriInst = lib_common.RemoteBox(hostOnly).UriMakeFromDict(className, dictProps)

		grph.add( ( rootNode, lib_common.MakeProp(className), uriInst ) )

		AddNamespaceLink(grph, rootNode, nameSpace, cimomUrl, className)

		# None properties are not printed.
		for inameKey in dictInst:
			# Do not print twice values which are in the name.
			if inameKey in splitMonik:
				continue
			inameVal = dictInst[inameKey]
			# TODO: If this is a reference, create a Node !!!!!!!
			if not inameVal is None:
				grph.add( ( uriInst, lib_common.MakeProp(inameKey), lib_common.NodeLiteral(inameVal) ) )

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

	cgiEnv.OutCgiRdf()
def Main():

    # TODO: The type should really be an integer.
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)

    # cimomUrl = cgiEnv.GetHost()
    # http://192.168.1.88
    machineName = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    cimomUrl = lib_wbem.HostnameToWbemServer(machineName)

    sys.stderr.write("wbem_hostname_processes.py cimomUrl=%s\n" % cimomUrl)

    # 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
    if lib_util.IsLocalAddress(machineName):
        machName_or_None = None
        serverBox = lib_common.gUriGen
    else:
        machName_or_None = machineName
        serverBox = lib_common.RemoteBox(machineName)

    # >>> conn = pywbem.WBEMConnection("http://192.168.1.88:5988" , ('pe***us','t*t*') )
    connWbem = lib_wbem.WbemConnection(cimomUrl)

    try:
        lstProc = connWbem.EnumerateInstances(ClassName="PG_UnixProcess",
                                              namespace="root/cimv2")
    except:
        lib_common.ErrorMessageHtml("Error:" + str(sys.exc_info()))

    # 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/rchateau/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>')

    # >>> lstProc[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 node are created once only.
    Main.dictWbemPidToNode = {}

    def WbemPidToNode(procId):
        sys.stderr.write("procId=%s\n" % procId)
        try:
            return Main.dictWbemPidToNode[procId]
        except KeyError:
            node = serverBox.PidUri(procId)

            Main.dictWbemPidToNode[procId] = node
            return node

    for oneProc in lstProc:
        node_process = WbemPidToNode(oneProc["Handle"])
        parent_node_process = WbemPidToNode(oneProc["ParentProcessID"])

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

        grph.add((node_process, pc.property_information,
                  lib_common.NodeLiteral(oneProc["Caption"])))

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

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

    cgiEnv.OutCgiRdf()
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)
    machineName = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    if lib_util.IsLocalAddress(machineName):
        machName_or_None = None
        serverBox = lib_common.gUriGen
    else:
        machName_or_None = machineName
        serverBox = lib_common.RemoteBox(machineName)

    try:
        loginImplicit = False  # IF FACT, WHY SHOULD IT BE SET ????????
        if loginImplicit or machName_or_None is None:
            # ESSAYER D UTILISER UNE EVENTUELLE CONNECTION PERSISTENTE ?? Non ca ne marche pas !!!!!
            cnnct = wmi.WMI(machineName)
        else:
            # persistent net connection
            # On a le probleme "access denied" avec tous les acces remote windows.
            # Meme probleme ausis avec WMI alors que ca marchait avant.
            # Comme s'il y avait une connection implicite de rchateau, quand ca marchait, et qu'elle ait disparu maintenant.
            # Toutefois, ceci fonctionne.
            # >>> c = wmi.WMI(wmi=wmi.connect_server(server='Titi', namespace="/root/cimv2", user='******', password='******'))

            sys.stderr.write("Explicit WMI connection machineName=%s\n" %
                             (machineName))

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

            #(wmiUser,wmiPass) = lib_credentials.GetCredentials("WMI",machineName)
            #sys.stderr.write("machineName= %wmiUser=%s\n" % ( machineName, wmiUser ) )
            #cnnct = wmi.WMI(wmi=wmi.connect_server(server=machineName, namespace="/root/cimv2", user=wmiUser, password=wmiPass))

    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("WMI " + machineName + " partitions:" +
                                    str(exc))

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

        for partition in physical_disk.associators(
                "Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators(
                    "Win32_LogicalDiskToPartition"):
                # BEWARE: What we call parition 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 = serverBox.DiskPartitionUri(logical_disk.Name)
                grph.add((node_partition, pc.property_information,
                          lib_common.NodeLiteral(logical_disk.Description)))

                grph.add((node_partition, pc.property_file_system_type,
                          lib_common.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((serverBox.DirectoryUri(logical_disk.Name),
                          pc.property_mount, node_partition))

    cgiEnv.OutCgiRdf()
Esempio n. 16
0
def DirToMenu(callbackGrphAdd, parentNode, entity_type, entity_id, entity_host,
              flagShowAll):
    def DirectoryUsabilityErrorNode(relative_dir, depthCall):
        # Maybe there is a usability test in the current module.
        # The goal is to control all scripts in the subdirectories, from here.
        try:
            entity_class = ".".join(relative_dir.split("/")[2:])
            #DirMenuReport( depthCall, "entity_class=%s\n"%(entity_class))

            importedMod = lib_util.GetEntityModule(entity_class)
            if importedMod:
                errorMsg = TestUsability(importedMod, entity_type,
                                         entity_ids_arr)
                # if flagShowAll and errorMsg ???
                if errorMsg:
                    DEBUG("IsDirectoryUsable errorMsg(1)=%s", errorMsg)
                    # If set to True, the directory is displayed even if all its scripts
                    # are not usable. Surprisingly, the message is not displayed as a subdirectory, but in a separate square.
                    return lib_common.NodeLiteral(errorMsg)
        except IndexError:
            # If we are at the top-level, no interest for the module.
            pass

        return None

    # This lists the scripts and generate RDF nodes.
    # Returns True if something was added.
    def DirToMenuAux(aParentNode,
                     grandParentNode,
                     curr_dir,
                     relative_dir,
                     depthCall=1):
        #DirMenuReport( depthCall, "curr_dir=%s relative_dir=%s\n"%(curr_dir,relative_dir))
        # In case there is nothing.
        dirs = None
        for path, dirs, files in os.walk(curr_dir):
            break

        # Maybe this class is not defined in our ontology.
        if dirs == None:
            WARNING("DirToMenuAux(2) No content in %s", curr_dir)
            return False

        # Will still be None if nothing is added.
        rdfNode = None
        sub_path = path[len(curr_dir):]

        relative_dir_sub_path = relative_dir + sub_path

        argDir = relative_dir_sub_path.replace("/", ".")[1:]

        # If this is a remote host, all scripts are checked because they might have
        # the flag CanProcessRemote which is defined at the script level, not the directory level.
        if not entity_host:
            errDirNode = DirectoryUsabilityErrorNode(relative_dir, depthCall)
            if errDirNode:
                if flagShowAll:
                    argDirSplit = argDir.split(".")
                    currDirNode = lib_util.DirDocNode(
                        ".".join(argDirSplit[:-1]), argDirSplit[-1])
                    if not currDirNode:
                        currDirNode = lib_util.NodeLiteral(
                            "Cannot parse relative dir:%s" % argDir)
                    callbackGrphAdd(
                        (grandParentNode, pc.property_script, currDirNode),
                        depthCall)
                    callbackGrphAdd((currDirNode, lib_common.MakeProp("Error"),
                                     errDirNode), depthCall)
                # The directory is not usable, so leave immediately.
                return False

        containsSomething = False
        for dir in dirs:
            #DirMenuReport( depthCall, "dir=%s\n"%(dir))
            # Might be generated by our Python interpreter.
            if dir == "__pycache__":
                continue

            full_sub_dir = os.path.join(curr_dir, dir)

            currDirNode = lib_util.DirDocNode(argDir, dir)

            if not currDirNode:
                #DirMenuReport( depthCall, "currDirNode NONE: argDir=%s dir=%s\n"%(argDir,dir))
                continue

            sub_relative_dir = relative_dir + "/" + dir

            sub_entity_class = ".".join(sub_relative_dir.split("/")[2:])
            ontoKeys = lib_util.OntologyClassKeys(sub_entity_class)
            #DirMenuReport( depthCall, "Checked ontology of %s: ontoKeys=%s\n"%(sub_entity_class,str(ontoKeys)))

            # TODO: Beware, if not ontology, returns empty array. Why not returning None ?
            if ontoKeys != []:
                #DirMenuReport( depthCall, "Module %s has an ontology so it is a class. Skipping\n"%(sub_relative_dir))
                # BEWARE: NO MORE DEFAULT ONTOLOGY ["Id"]
                continue

            somethingAdded = DirToMenuAux(currDirNode, aParentNode,
                                          full_sub_dir, sub_relative_dir,
                                          depthCall + 1)
            # This adds the directory name only if it contains a script.
            if somethingAdded:
                # It works both ways, possibly with different properties.
                callbackGrphAdd((aParentNode, pc.property_script, currDirNode),
                                depthCall)
            containsSomething = containsSomething | somethingAdded

        for fil in files:
            # We want to list only the usable Python scripts.
            if not fil.endswith(".py") or fil == "__init__.py":
                continue

            script_path = relative_dir_sub_path + "/" + fil

            #DirMenuReport( depthCall, "DirToMenu encodedEntityId=%s\n" % encodedEntityId)

            url_rdf = genObj.MakeTheNodeFromScript(script_path, entity_type,
                                                   encodedEntityId)

            errorMsg = None

            try:
                importedMod = lib_util.GetScriptModule(argDir, fil)
            except Exception:
                errorMsg = sys.exc_info()[1]
                #DirMenuReport( depthCall, "DirToMenuAux Cannot import=%s. Caught: %s\n" % (script_path, errorMsg ) )
                importedMod = None
                if not flagShowAll:
                    continue

            if not errorMsg:
                # Show only scripts which want to be shown. Each script can have an optional function
                # called Usable(): If it is there and returns False, the script is not displayed.
                errorMsg = TestUsability(importedMod, entity_type,
                                         entity_ids_arr)
                if errorMsg:
                    pass
                    #DEBUG("DirToMenuAux errorMsg(2)=%s",errorMsg)

            # If this is a local host
            if not flagShowAll and errorMsg and not entity_host:
                continue

            # If the entity is on another host, does the script run on remote entities ?
            # The concept of "CanProcessRemote" is a short-hand to avoid checking
            # if the remote is in the entity ids. This flag means:
            # "It is worth anyway investigating on a remote host, if the entity exists there."
            if entity_host:
                try:
                    # Script can be used on a remote entity.
                    can_process_remote = importedMod.CanProcessRemote
                except AttributeError:
                    can_process_remote = False

                # can_process_remote = True
                DEBUG(
                    "entity_dir_menu.py DirToMenuAux entity_host=%s can_process_remote=%d",
                    entity_host, can_process_remote)

                if not can_process_remote:
                    if not errorMsg:
                        errorMsg = "%s is local" % (entity_host)
                    # DirMenuReport( depthCall, "Script %s %s cannot work on remote entities: %s at %s\n" % ( argDir, fil, encodedEntityId , entity_host ) )
                    #DirMenuReport( depthCall, "Script %s %s cannot work on remote entities\n" % ( argDir, fil ) )

                    if not flagShowAll:
                        continue
                else:
                    DirMenuReport(
                        depthCall,
                        "Script %s %s CAN work on remote entities\n" %
                        (argDir, fil))

            # Here, we are sure that the script is added.
            # TODO: If no script is added, should not add the directory?
            rdfNode = lib_common.NodeUrl(url_rdf)
            callbackGrphAdd((aParentNode, pc.property_script, rdfNode),
                            depthCall)

            # Default doc text is file name minus the ".py" extension.
            nodModu = lib_util.FromModuleToDoc(importedMod, fil[:-3])

            callbackGrphAdd((rdfNode, pc.property_information, nodModu),
                            depthCall)

            if errorMsg:
                callbackGrphAdd((rdfNode, lib_common.MakeProp("Error"),
                                 lib_common.NodeLiteral(errorMsg)), depthCall)

        # This tells if a script was added in this directory or one of the subdirs.
        return (rdfNode is not None) | containsSomething

    if entity_host:
        DEBUG("entity_dir_menu.py DirToMenu entity_host=%s", entity_host)
    encodedEntityId = lib_util.EncodeUri(entity_id)
    entity_ids_arr = lib_util.EntityIdToArray(entity_type, entity_id)

    if entity_type:
        # entity_type might contain a slash, for example: "sqlite/table"
        relative_dir = "/sources_types/" + entity_type
    else:
        relative_dir = "/sources_types"

    directory = lib_util.gblTopScripts + relative_dir

    if entity_host:
        genObj = lib_common.RemoteBox(entity_host)
    else:
        genObj = lib_common.gUriGen

    DirToMenuAux(parentNode, None, directory, relative_dir, depthCall=1)
Esempio n. 17
0
        # TODO: Should check if this property is different for all instances !!!
        withExtraArgs = {propDiscrim: dictInst[propDiscrim]}
        allArgs = splitMonik.copy()
        allArgs.update(withExtraArgs)
        dictProps = allArgs
    else:
        dictProps = splitMonik

    # uriInst = lib_util.EntityUriFromDict( className, dictProps  )
    # uriInst = lib_common.RemoteBox(cimomUrl).UriMakeFromDict(className, dictProps)

    hostOnly = lib_util.EntHostToIp(cimomUrl)
    if lib_util.IsLocalAddress(hostOnly):
        uriInst = lib_common.gUriGen.UriMakeFromDict(className, dictProps)
    else:
        uriInst = lib_common.RemoteBox(hostOnly).UriMakeFromDict(
            className, dictProps)

    # PEUT-ETRE UTILISER LA VERITABLE CLASSE, MAIS IL FAUT PART LA SUITE ATTEINDRE LA CLASSE DE BASE.
    grph.add((rootNode, lib_common.MakeProp(className), uriInst))

    # None properties are not printed.
    for inameKey in dictInst:
        # Do not print twice values which are in the name.
        if inameKey in splitMonik:
            continue
        inameVal = dictInst[inameKey]
        # TODO: If this is a reference, create a Node !!!!!!!
        if not inameVal is None:
            grph.add((uriInst, lib_common.MakeProp(inameKey),
                      lib_common.NodeLiteral(inameVal)))
Esempio n. 18
0
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    # TODO: Try this on a remote machine.
    server = None  # Run on local machine for the moment.

    # servName_or_None is for Windows functions where the local host must be None.
    # servNameNotNone is for our URLs where the hostname must be explicit.
    if not server or lib_util.IsLocalAddress(server):
        servName_or_None = None

        # So it is compatible with WMI.
        servNameNotNone = lib_uris.TruncateHostname(lib_util.currentHostname)
        # .home
        serverNode = lib_common.nodeMachine
        serverBox = lib_common.gUriGen
    else:
        servName_or_None = server
        servNameNotNone = server
        serverNode = lib_common.gUriGen.HostnameUri(server)
        serverBox = lib_common.RemoteBox(server)

    resume = 0
    numMembers = 0
    while True:
        level = 1
        data, total, resume = win32net.NetLocalGroupEnum(
            servName_or_None, level, resume)
        for group in data:
            # sys.stderr.write("Group %(name)s:%(comment)s\n" % group)

            # TODO: Not sure about the groupname syntax.
            groupName = group['name']
            # nodeGroup = lib_common.gUriGen.GroupUri( groupName )
            nodeGroup = survol_Win32_Group.MakeUri(groupName, servNameNotNone)

            grph.add((nodeGroup, pc.property_host, lib_common.nodeMachine))
            groupComment = group['comment']
            if groupComment != "":
                groupCommentMaxWidth = max(80, len(groupName))
                if len(groupComment) > groupCommentMaxWidth:
                    groupComment = groupComment[:groupCommentMaxWidth] + "..."
                grph.add((nodeGroup, pc.property_information,
                          lib_common.NodeLiteral(groupComment)))

            memberresume = 0
            while True:
                levelMember = 2
                memberData, total, memberResume = win32net.NetLocalGroupGetMembers(
                    server, group['name'], levelMember, memberresume)
                for member in memberData:
                    # Converts Sid to username
                    userName, domain, type = win32security.LookupAccountSid(
                        servName_or_None, member['sid'])
                    numMembers = numMembers + 1
                    # sys.stderr.write("    Member: %s: %s\n" % (userName, member['domainandname']))
                    # nodeUser = lib_common.gUriGen.UserUri( userName )
                    nodeUser = survol_Win32_UserAccount.MakeUri(
                        userName, servNameNotNone)

                    # TODO: Not sure about the property.
                    # TODO: Not sure about the username syntax.
                    grph.add((nodeUser, pc.property_group, nodeGroup))
                if memberResume == 0:
                    break
        if not resume:
            break

    cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
Esempio n. 19
0
def DirToMenuAux(callbackGrphAdd,parentNode,curr_dir,relative_dir,entity_type,entity_ids_arr,encodedEntityId,entity_host,flagShowAll,depthCall = 1):
	# sys.stderr.write("DirToMenuAux entity_host=%s\n"%(entity_host) )
	# DirMenuReport( depthCall, "curr_dir=%s relative_dir=%s\n"%(curr_dir,relative_dir))
	# In case there is nothing.
	dirs = None
	for path, dirs, files in os.walk(curr_dir):
		break

	# Maybe this class is not defined in our ontology.
	if dirs == None:
		# sys.stderr.write("No content in "+curr_dir)
		return False

	# Will still be None if nothing is added.
	rdfNode = None
	sub_path = path[ len(curr_dir) : ]

	relative_dir_sub_path = relative_dir + sub_path

	argDir = relative_dir_sub_path.replace("/",".")[1:]

	# Maybe there is a usability test in the current module.
	# The goal is to control all scripts in the subdirectories, from here.
	try:
		entity_class = ".".join( relative_dir.split("/")[2:] )
		# DirMenuReport( depthCall, "entity_class=%s\n"%(entity_class))

		importedMod = lib_util.GetEntityModule(entity_class)
		if importedMod:
			errorMsg = TestUsability(importedMod,entity_type,entity_ids_arr)
			# if flagShowAll and errorMsg ???
			if errorMsg:
				# If set to True, the directory is displayed even if all its scripts
				# are not usable. Surprisingly, the message is not displayed as a subdirectory, but in a separate square.
				if False:
					callbackGrphAdd( ( parentNode, lib_common.MakeProp("Usability"), lib_common.NodeLiteral(errorMsg) ),depthCall )
				return False
	except IndexError:
		# If we are at the top-level, no interest for the module.
		pass


	containsSomething = False
	for dir in dirs:
		# DirMenuReport( depthCall, "dir=%s\n"%(dir))
		# Might be generated by our Python interpreter.
		if dir == "__pycache__":
			continue

		full_sub_dir = curr_dir + "/" + dir
		full_sub_dir = full_sub_dir.replace("\\","/")

		currDirNode = lib_util.DirDocNode(argDir,dir)

		if not currDirNode:
			DirMenuReport( depthCall, "currDirNode NONE: argDir=%s dir=%s\n"%(argDir,dir))
			continue

		sub_relative_dir = relative_dir + "/" + dir

		sub_entity_class = ".".join( sub_relative_dir.split("/")[2:] )
		ontoKeys = lib_util.OntologyClassKeys(sub_entity_class)
		# DirMenuReport( depthCall, "Checked ontology of %s: ontoKeys=%s\n"%(sub_entity_class,str(ontoKeys)))

		# TODO: Beware, if not ontology, returns empty array. Why not returning None ?
		if ontoKeys != []:
			# DirMenuReport( depthCall, "Module %s has an ontology so it is a class. Skipping\n"%(sub_relative_dir))
			# BEWARE: NO MORE DEFAULT ONTOLOGY ["Id"]
			continue

		somethingAdded = DirToMenuAux(callbackGrphAdd,currDirNode, full_sub_dir,sub_relative_dir,entity_type,entity_ids_arr,encodedEntityId,entity_host,flagShowAll,depthCall + 1)
		# This adds the directory name only if it contains a script.
		if somethingAdded:
			# CA MARCHE DANS LES DEUX CAS. SI PROPRIETE DIFFERENTE, ON AURA SIMPLEMENT DEUX PAVES, UN POUR LES DIR, L AUTRE POUR LES FICHIERS.
			# grph.add( ( parentNode, pc.property_directory, currDirNode ) )
			callbackGrphAdd( ( parentNode, pc.property_script, currDirNode ), depthCall )
		containsSomething = containsSomething | somethingAdded

	for fil in files:
		# We want to list only the usable Python scripts.
		if not fil.endswith(".py") or fil == "__init__.py":
			continue

		script_path = relative_dir_sub_path + "/" + fil

		# DirMenuReport( depthCall, "DirToMenu encodedEntityId=%s\n" % encodedEntityId)
		if entity_host:
			genObj = lib_common.RemoteBox(entity_host)
		else:
			genObj = lib_common.gUriGen

		url_rdf = genObj.MakeTheNodeFromScript( script_path, entity_type, encodedEntityId )

		errorMsg = None

		try:
			importedMod = lib_util.GetScriptModule(argDir, fil)
		except Exception:
			errorMsg = sys.exc_info()[1]
			DirMenuReport( depthCall, "Cannot import=%s. Caught: %s\n" % (script_path, errorMsg ) )
			importedMod = None
			if not flagShowAll:
				continue

		if not errorMsg:
			# Show only scripts which want to be shown. Each script can have an optional function
			# called Usable(): If it is there and returns False, the script is not displayed.
			errorMsg = TestUsability(importedMod,entity_type,entity_ids_arr)

		if not flagShowAll and errorMsg:
			continue

		# If the entity is on another host, does this work on remote entities ?
		if entity_host:
			try:
				# Script can be used on a remote entity.
				can_process_remote = importedMod.CanProcessRemote
			except AttributeError:
				can_process_remote = False

			can_process_remote = True
			if not can_process_remote:
				if not errorMsg:
					errorMsg = "%s is local" % ( entity_host )
				DirMenuReport( depthCall, "Script %s %s cannot work on remote entities: %s at %s\n" % ( argDir, fil, encodedEntityId , entity_host ) )

				if not flagShowAll:
					continue

		# Here, we are sure that the script is added.
		# TODO: If no script is added, should not add the directory?
		rdfNode = lib_common.NodeUrl(url_rdf)
		callbackGrphAdd( ( parentNode, pc.property_script, rdfNode ), depthCall )

		# Default doc text is file name minus the ".py" extension.
		nodModu = lib_util.FromModuleToDoc(importedMod,fil[:-3])

		callbackGrphAdd( ( rdfNode, pc.property_information, nodModu ), depthCall )

		if errorMsg:
			callbackGrphAdd( ( rdfNode, lib_common.MakeProp("Error"), lib_common.NodeLiteral(errorMsg) ), depthCall )

	# This tells if a script was added in this directory or one of the subdirs.
	return ( rdfNode is not None ) | containsSomething
Esempio n. 20
0
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)

    server = cgiEnv.m_entity_id_dict["Domain"]
    groupName = cgiEnv.m_entity_id_dict["Name"]

    grph = cgiEnv.GetGraph()

    # http://www.math.uiuc.edu/~gfrancis/illimath/windows/aszgard_mini/movpy-2.0.0-py2.4.4/movpy/lib/win32/Demos/win32netdemo.py

    # hostname = "Titi" for example
    try:
        lib_win32.WNetAddConnect(server)
    except:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Server=%s Caught:%s" % (server, str(exc)))

    if not server or lib_util.IsLocalAddress(server):
        servName_or_None = None

        # So it is compatible with WMI.
        servNameNotNone = lib_uris.TruncateHostname(lib_util.currentHostname)
        # .home
        serverNode = lib_common.nodeMachine
        serverBox = lib_common.gUriGen
    else:
        servName_or_None = server
        servNameNotNone = server
        serverNode = lib_common.gUriGen.HostnameUri(server)
        serverBox = lib_common.RemoteBox(server)

    # nodeGroup = serverBox.GroupUri( groupName )
    # nodeGroup = survol_Win32_Group.MakeUri( groupName, servName_or_None )
    nodeGroup = survol_Win32_Group.MakeUri(groupName, servNameNotNone)

    try:
        memberresume = 0
        while True:
            memberData, total, memberResume = win32net.NetLocalGroupGetMembers(
                servName_or_None, groupName, 2, memberresume)
            for member in memberData:
                sidUsage = member['sidusage']
                # Converts Sid to username
                try:
                    memberName, domain, type = win32security.LookupAccountSid(
                        server, member['sid'])
                except Exception:
                    exc = sys.exc_info()[1]
                    ERROR("Server=%s Caught:%s", server, str(exc))
                    continue

                DEBUG("Member: %s:", str(member))
                DEBUG("Lookup: %s: %s", memberName, member['domainandname'])
                # nodeUser = serverBox.UserUri( userName )

                DEBUG("servNameNotNone=%s", servNameNotNone)
                memberNode = MemberNameToNode(sidUsage, memberName,
                                              servNameNotNone)

                grph.add((memberNode, pc.property_group, nodeGroup))
                grph.add((memberNode, lib_common.MakeProp("SID Usage"),
                          lib_common.NodeLiteral(SidUsageToString(sidUsage))))
                grph.add(
                    (memberNode, lib_common.MakeProp("Security Identifier"),
                     lib_common.NodeLiteral(member['sid'])))

                if servName_or_None:
                    nodeMemberRemote = MemberNameToNodeRemote(
                        sidUsage, memberName, servName_or_None, serverBox)
                    # TODO: Instead, both object must have the same universal alias
                    grph.add((memberNode, pc.property_alias, nodeMemberRemote))

            if memberResume == 0:
                break
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("win32 local groups:" + str(exc))

    cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
Esempio n. 21
0
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)
    pid = int(cgiEnv.GetId())
    machineName = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    if (machineName == lib_util.currentHostname) or (not machineName):
        #machName_or_None = None
        serverBox = lib_common.gUriGen
    else:
        #machName_or_None = machineName
        serverBox = lib_common.RemoteBox(machineName)

    node_process = serverBox.PidUri(pid)

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

    # lstProcs = cnnct.Win32_Process(Handle=pid)
    # 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

    lstPropNames = [
        "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"
    ]

    className = "CIM_Process"

    mapPropUnits = lib_wmi.WmiDictPropertiesUnit(cnnct, className)

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

        for prpProc in lstPropNames:
            valProc = getattr(wmiProc, prpProc)
            try:
                valUnit = mapPropUnits[prpProc]
            except KeyError:
                valUnit = ""
            valProcUnit = lib_util.AddSIUnit(valProc, valUnit)
            grph.add((node_process, lib_common.MakeProp(prpProc),
                      lib_common.NodeLiteral(valProcUnit)))

        parent_node_process = serverBox.PidUri(wmiProc.ParentProcessId)
        grph.add((node_process, pc.property_ppid, parent_node_process))

    cgiEnv.OutCgiRdf()
def Main():
	cgiEnv = lib_common.CgiEnv(can_process_remote = True)
	server = cgiEnv.GetId()

	if lib_util.IsLocalAddress( server ):
		server = None

	grph = cgiEnv.GetGraph()

	# http://www.math.uiuc.edu/~gfrancis/illimath/windows/aszgard_mini/movpy-2.0.0-py2.4.4/movpy/lib/win32/Demos/win32netdemo.py
	# servName_or_None, imper = lib_win32.MakeImpersonate(server)

	# hostname = "Titi" for example
	try:
		lib_win32.WNetAddConnect(server)
	except:
		# Maybe the machine is not online.
		exc = sys.exc_info()[1]
		lib_common.ErrorMessageHtml(str(exc))

	# It might be an empty string.
	if server:
		servName_or_None = server
	else:
		servName_or_None = None

	if servName_or_None:
		serverNode = lib_common.gUriGen.HostnameUri(server)
		serverBox = lib_common.RemoteBox(server)
	else:
		serverNode = lib_common.nodeMachine
		serverBox = lib_common.gUriGen

	resume = 0
	numMembers = 0
	try:
		while True:
			# data, total, resume = win32net.NetLocalGroupEnum(server, 1, resume)
			data, total, resume = win32net.NetLocalGroupEnum(servName_or_None, 1, resume)
			for group in data:
				sys.stderr.write("Group %(name)s:%(comment)s\n" % group)

				# TODO: Not sure about the groupname syntax.
				groupName = group['name']
				sys.stderr.write("groupName=%s\n" % groupName)
				# nodeGroup = serverBox.GroupUri( groupName )
				nodeGroup = survol_Win32_Group.MakeUri( groupName, servName_or_None )

				grph.add( ( nodeGroup, pc.property_host, serverNode ) )
				groupComment = group['comment']
				sys.stderr.write("groupComment=%s\n" % groupComment)
				if groupComment != "":
					groupCommentMaxWidth = max( 80, len(groupName) )
					if len(groupComment) > groupCommentMaxWidth:
						groupComment = groupComment[:groupCommentMaxWidth] + "..."
					grph.add( (nodeGroup, pc.property_information, lib_common.NodeLiteral(groupComment) ) )

				memberresume = 0
				while True:
					# memberData, total, memberResume = win32net.NetLocalGroupGetMembers(server, group['name'], 2, resume)
					memberData, total, memberResume = win32net.NetLocalGroupGetMembers(servName_or_None, group['name'], 2, memberresume)
					for member in memberData:
						# Converts Sid to username
						numMembers = numMembers + 1
						try:
							userName, domain, type = win32security.LookupAccountSid(server, member['sid'])
						except Exception:
							exc = sys.exc_info()[1]
							sys.stderr.write("Server=%s Caught:%s\n" % ( server, str(exc) ) )
							continue

						sys.stderr.write("    Member: %s: %s\n" % (userName, member['domainandname']))
						# nodeUser = serverBox.UserUri( userName )
						nodeUser = survol_Win32_UserAccount.MakeUri( userName, servName_or_None )

						# TODO: Not sure about the property.
						# TODO: Not sure about the username syntax.
						grph.add( (nodeUser, pc.property_group, nodeGroup ) )
					if memberResume==0:
						break
			if not resume:
				break
	except Exception:
		exc = sys.exc_info()[1]
		lib_common.ErrorMessageHtml("win32 local groups:"+str(exc))

	cgiEnv.OutCgiRdf("LAYOUT_SPLINE")