Exemple #1
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():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    dsnNam = survol_odbc_dsn.GetDsnNameFromCgi(cgiEnv)
    sessionId = cgiEnv.m_entity_id_dict["SessionId"]

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

    nodeSession = 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)

        grph.add((nodeSession, lib_common.MakeProp("Session id"),
                  lib_common.NodeLiteral(sessionId)))
        GetInfoConnections(grph, sessionId, nodeSession, cnxn)
        GetInfoSessions(grph, sessionId, nodeSession, cnxn)
        GetInfoRequests(grph, sessionId, nodeSession, cnxn, dsnNam)

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

    cgiEnv.OutCgiRdf()
Exemple #3
0
def Main():
	cgiEnv = lib_common.ScriptEnvironment()

	grph = cgiEnv.GetGraph()

	rpmProps = survol_rpm.rpm_properties()

	rpmPropName = lib_common.MakeProp("rpm")

	try:
		ts = rpm.TransactionSet()
		mi = ts.dbMatch()
		for h in mi:
			rpmName = h['name']

			nodeRpm = survol_rpm.MakeUri(rpmName)
			# Unfortunately, it does not seem to work to force the type.
			# TODO: Maybe this is because we later try to convert to a number,
			# without checking the type of the data ???
			for propKey in rpmProps:
				propRpm = rpmProps[propKey]
				# The value might be None.
				propVal = h[propKey] or ""
				grph.add((nodeRpm, propRpm, lib_util.NodeLiteral(propVal)))

			grph.add((lib_common.nodeMachine, rpmPropName, nodeRpm))
	except Exception as exc:
		lib_common.ErrorMessageHtml("List of RPMs: Error %s" % str(exc))

	cgiEnv.OutCgiRdf("LAYOUT_RECT", [rpmPropName])
Exemple #4
0
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    listVMs = survol_java.ListJavaProcesses()

    #listVMs = jvPckVM.list()
    DEBUG("VirtualMachine.list=:")
    for thePid in listVMs:
        node_process = lib_common.gUriGen.PidUri(thePid)
        theProcObj = listVMs[thePid]
        for theKey in theProcObj:
            theVal = theProcObj[theKey]
            if theVal is None:
                strVal = ""
            else:
                try:
                    strVal = str(theVal)
                except:
                    strVal = "No value"
            DEBUG("%s = %s", theKey, strVal)

            grph.add((node_process, lib_common.MakeProp(theKey),
                      lib_common.NodeLiteral(strVal)))

    cgiEnv.OutCgiRdf()
Exemple #5
0
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    cgroupName = cgiEnv.GetId()
    cgroupNode = survol_cgroup.MakeUri(cgroupName)

    propCGroup = lib_common.MakeProp("cgroup")

    # This file contains all processes belonging to this cgroup.
    # Example "/sys/fs/cgroup/cpuset/cgroup.procs"
    # Read access might be forbidden.
    filNamCGroup = "/sys/fs/cgroup/%s/cgroup.procs" % cgroupName

    try:
        for lin_cg in open(filNamCGroup):
            procId = int(lin_cg)
            procNode = lib_common.gUriGen.PidUri(procId)

            grph.add((cgroupNode, propCGroup, procNode))
    except:
        ERROR("Invalid cgroup:%s", cgroupName)
        lib_common.ErrorMessageHtml("Invalid cgroup:%s" % cgroupName)

    # This lists processes in a table instead of scattered nodes.
    # This is because there might be a lot of processes.
    cgiEnv.OutCgiRdf("LAYOUT_RECT", [propCGroup])
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    dsn_nam = cgiEnv.m_entity_id_dict["Dsn"]
    session_id = cgiEnv.m_entity_id_dict["SessionId"]

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

    node_session = 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)

        grph.add((node_session, lib_common.MakeProp("Session id"),
                  lib_util.NodeLiteral(session_id)))
        _get_info_connections(grph, session_id, node_session, cnxn)
        _get_info_sessions(grph, session_id, node_session, cnxn)
        _get_info_requests(grph, session_id, node_session, cnxn, dsn_nam)

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

    cgiEnv.OutCgiRdf()
def Main():
    # If this flag is set, the script uses SLP to discover Survol 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()

    _survol_servers_display(grph)

    if flag_slp:
        dict_services = survol_neighborhood.GetSLPServices("survol")
        for key_service in dict_services:
            node_survol_url = _callback_node_adder(grph, key_service)
            grph.add((node_survol_url,
                      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((node_survol_url, prop_attr, lib_util.NodeLiteral(val_attr)))

    cgiEnv.OutCgiRdf()
def Main():
    cgiEnv = lib_common.CgiEnv()
    pid = int(cgiEnv.GetId())

    grph = cgiEnv.GetGraph()

    proc_obj = CIM_Process.PsutilGetProcObj(pid)

    nodeProcess = lib_common.gUriGen.PidUri(pid)

    try:
        all_maps = CIM_Process.PsutilProcMemmaps(proc_obj)
    except:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("get_memory_maps Pid=%d. Caught %s\n" %
                                    (pid, str(exc)))

    propMemoryRSS = lib_common.MakeProp("Resident Set Size")
    for map in all_maps:
        # This, because all Windows paths are "standardized" by us.
        cleanMapPath = map.path.replace("\\", "/")

        uriMemMap = lib_common.gUriGen.MemMapUri(cleanMapPath)

        grph.add((uriMemMap, propMemoryRSS, lib_common.NodeLiteral(map.rss)))
        grph.add((nodeProcess, pc.property_memmap, uriMemMap))

    cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
Exemple #9
0
def Main():
    cgiEnv = lib_oracle.OracleEnv()

    oraPackage = cgiEnv.m_entity_id_dict["Package"]
    oraSchema = cgiEnv.m_entity_id_dict["Schema"]

    grph = cgiEnv.GetGraph()

    node_oraPackage = oracle_package.MakeUri(cgiEnv.m_oraDatabase, oraSchema,
                                             oraPackage)

    node_oraSchema = oracle_schema.MakeUri(cgiEnv.m_oraDatabase, oraSchema)
    grph.add((node_oraSchema, pc.property_oracle_package, node_oraPackage))

    # TODO: This is problematic as these could also be functions.
    # TODO: But when joining with ALL_OBJECTS, most rows are gone. So what to do ?
    sql_query = "select distinct procedure_name from all_procedures where object_type='PACKAGE' " \
       "and owner='" + oraSchema + "' and object_name='" + oraPackage + "'"
    sys.stderr.write("sql_query=%s\n" % sql_query)
    result = lib_oracle.ExecuteQuery(cgiEnv.ConnectStr(), sql_query)

    propProcToPackage = lib_common.MakeProp("Package")
    for row in result:
        procedureName = row[0]
        procedureNode = oracle_procedure.MakeUri(cgiEnv.m_oraDatabase,
                                                 oraSchema, procedureName)
        grph.add((node_oraPackage, propProcToPackage, procedureNode))

    cgiEnv.OutCgiRdf("LAYOUT_SPLINE", [propProcToPackage])
def Main():
	cgiEnv = lib_common.CgiEnv()

	grph = cgiEnv.GetGraph()

	#pidNum = cgiEnv.m_entity_id_dict["Pid"]
	#filNam = cgiEnv.m_entity_id_dict["File"]
	#sqlQuery_encode = cgiEnv.m_entity_id_dict["Query"]

	# sqlQuery_encode = cgiEnv.GetId()
	# TODO: This should be packaged in sql/__init__.py.
	#sqlQuery = lib_util.Base64Decode(sqlQuery_encode)

	sqlQuery = sql_query.GetEnvArgs(cgiEnv)

	nodeSqlQuery = sql_query.MakeUri(sqlQuery)

	propSheetToQuery = lib_common.MakeProp("Table dependency")

	list_of_tables = lib_sql.TableDependencies(sqlQuery)

	# Based on the pid and the filnam, find which database connection it is.


	for tabNam in list_of_tables:
		nodTab = sheet.MakeUri(tabNam)

		grph.add( ( nodeSqlQuery, propSheetToQuery, nodTab ) )

	cgiEnv.OutCgiRdf()
Exemple #11
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))))
Exemple #12
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
Exemple #13
0
def Main():
	cgiEnv = lib_common.CgiEnv()
	pid_as_integer = int(cgiEnv.GetId())

	grph = cgiEnv.GetGraph()

	node_process = lib_common.gUriGen.PidUri(pid_as_integer)

	dict_regex_sql = lib_sql.SqlRegularExpressions()

	arr_props = []

	# TODO: Unfortunately it scans several times the memory process.
	for rgx_key in dict_regex_sql:
		rgx_sql = dict_regex_sql[rgx_key]
		regex_predicate = lib_common.MakeProp(rgx_key)
		arr_props.append(regex_predicate)

		try:
			# https://docs.python.org/3/library/re.html
			# re.MULTILINE | re.ASCII | re.IGNORECASE
			matched_sqls = memory_regex_search.GetRegexMatches(pid_as_integer, rgx_sql, re.IGNORECASE)
		except Exception as exc:
			lib_common.ErrorMessageHtml("Error:%s. Protection ?" % str(exc))

		all_queries_set = set()

		for sql_idx in matched_sqls:
			sql_qry = matched_sqls[sql_idx]
			_process_scanned_sql_query(sql_qry, all_queries_set)

		_generate_from_sql_queries(grph, node_process, regex_predicate, all_queries_set, pid_as_integer)

	cgiEnv.OutCgiRdf("LAYOUT_RECT",arr_props)
Exemple #14
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    grph = cgiEnv.GetGraph()

    listVMs = survol_java.ListJavaProcesses()

    #listVMs = jvPckVM.list()
    logging.debug("VirtualMachine.list=:")
    for the_pid in listVMs:
        node_process = lib_uris.gUriGen.PidUri(the_pid)
        the_proc_obj = listVMs[the_pid]
        for the_key in the_proc_obj:
            theVal = the_proc_obj[the_key]
            if theVal is None:
                str_val = ""
            else:
                try:
                    str_val = str(theVal)
                except:
                    str_val = "No value"
            logging.debug("%s = %s", the_key, str_val)

            grph.add((node_process, lib_common.MakeProp(the_key),
                      lib_util.NodeLiteral(str_val)))

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

    node_host = lib_uris.gUriGen.HostnameUri(hostname)

    grph = cgiEnv.GetGraph()

    # Return the name of the computer, name of the user, and active and idle times for the session.
    # No special group membership is required for level 0 or level 10 calls.
    level = 10

    try:
        lib_win32.WNetAddConnect(hostname)

        session_list = win32net.NetSessionEnum(level, hostname)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Hostname=" + hostname + ". Exception:" +
                                    str(exc))

    for elt_lst in session_list:
        for key_lst in elt_lst:
            val_lst = elt_lst[key_lst]
            grph.add((node_host, lib_common.MakeProp(key_lst),
                      lib_util.NodeLiteral(val_lst)))

    cgiEnv.OutCgiRdf()
def Main():
    # cgiEnv = lib_common.CgiEnv()
    cgiEnv = lib_oracle.OracleEnv()

    grph = cgiEnv.GetGraph()

    sqlQuery = sql_query.GetEnvArgs(cgiEnv)
    dbNam = cgiEnv.m_entity_id_dict["Db"]

    # This is simply the user.
    oraSchema = cgiEnv.OracleSchema()

    nodeSqlQuery = oracle_query.MakeUri(sqlQuery, dbNam)

    propSheetToQuery = lib_common.MakeProp("Table dependency")

    list_of_table_names = lib_sql.TableDependencies(sqlQuery)

    list_of_nodes = oracle_query.QueryToNodesList(sqlQuery, {"Db": dbNam},
                                                  list_of_table_names,
                                                  oraSchema)

    for nodTab in list_of_nodes:
        grph.add((nodeSqlQuery, propSheetToQuery, nodTab))

    cgiEnv.OutCgiRdf()
Exemple #17
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_odbc_dsn.MakeUri(dsnNam)

    ODBC_ConnectString = survol_odbc_dsn.MakeOdbcConnectionString(dsnNam)

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

        # for prmstr in sqlgetinfo_params:
        for prmstr in dir(pyodbc):
            if not prmstr.startswith("SQL_"):
                continue
            #sys.stderr.write("prmstr: %s\n" % prmstr)

            # 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 AttributeError:
            except:
                grph.add(
                    (nodeDsn, prop, lib_common.NodeLiteral("Unavailable")))
                continue

            try:
                prm_value = cnxn.getinfo(prm)
            except:
                #txt = str( sys.exc_info()[1] )
                #grph.add( (nodeDsn, prop, lib_common.NodeLiteral(txt) ) )
                continue

            try:
                grph.add((nodeDsn, prop, lib_common.NodeLiteral(prm_value)))
            except:
                txt = str(sys.exc_info()[1])
                grph.add((nodeDsn, prop, lib_common.NodeLiteral(txt)))
                continue

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

    cgiEnv.OutCgiRdf()
Exemple #18
0
def Main():
	cgiEnv = lib_common.CgiEnv()

	grph = cgiEnv.GetGraph()

	credNames = lib_credentials.GetCredentialsNames( "MySql" )
	sys.stderr.write("Mysql servers\n")

	for instanceMySql in credNames:
		sys.stderr.write("WbemServersList instanceMySql=%s\n"%(instanceMySql))

		# Do not use sources_types.mysql
		hostMySql = instanceMySql.split(":")[0]

		# TODO: Display the connection socket ?
		nodeHostMySql = lib_common.gUriGen.HostnameUri( hostMySql )

		# Intentionaly, it does not use mysql package.
		# nodeInstance = lib_common.gUriGen.UriMakeFromDict("mysql/instance", { "Instance": instanceMySql } )
		nodeInstance = survol_mysql_instance.MakeUri(instanceMySql)

		aCred = lib_credentials.GetCredentials( "MySql", instanceMySql )

		grph.add( ( nodeInstance, pc.property_user, lib_common.NodeLiteral(aCred[0]) ) )
		grph.add( ( nodeInstance, lib_common.MakeProp("Mysql instance"), nodeHostMySql ) )



	try:
		pass
	except Exception:
		exc = sys.exc_info()[1]
		lib_common.ErrorMessageHtml("tnsnam="+tnsnam+" err="+str(exc))

	cgiEnv.OutCgiRdf()
Exemple #19
0
def Main():
    # If this flag is set, the script uses SLP to discover WBEM Agents.
    paramkeySLP = "Service Location Protocol"

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

    flagSLP = bool(cgiEnv.get_parameters(paramkeySLP))

    grph = cgiEnv.GetGraph()

    WbemServersDisplay(grph)

    if flagSLP:
        dictServices = survol_neighborhood.GetSLPServices("survol")
        for keyService in dictServices:
            wbemNode = AddFromWbemCimom(grph, keyService)

            if not wbemNode:
                continue

            grph.add((wbemNode, pc.property_information,
                      lib_common.NodeLiteral("Service Location Protocol")))

            attrsService = dictServices[keyService]
            for keyAttr in attrsService:
                propAttr = lib_common.MakeProp(keyAttr)
                valAttr = attrsService[keyAttr]
                grph.add((wbemNode, propAttr, lib_common.NodeLiteral(valAttr)))

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

    grph = cgiEnv.GetGraph()

    node_process = lib_uris.gUriGen.PidUri(pidint)

    try:
        rgx_http = r"\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}"

        resu_com_classes = memory_regex_search.GetRegexMatches(
            pidint, rgx_http)

        prop_com_class = lib_common.MakeProp("COM class")
        for class_idx in resu_com_classes:
            com_class_id = resu_com_classes[class_idx]
            # On Python3, this is a bytes which must be converted to str.
            com_class_id = str(com_class_id)

            # comClass = "{DB7A405D-208F-4E88-BA0A-132ACFA0B5B6}" for example.
            typelib_node = lib_uris.gUriGen.ComRegisteredTypeLibUri(
                com_class_id)
            grph.add((node_process, prop_com_class, typelib_node))

    except Exception as exc:
        lib_common.ErrorMessageHtml("Error:%s. Protection ?" % str(exc))

    cgiEnv.OutCgiRdf()
Exemple #21
0
def Main():
    cgiEnv = lib_common.CgiEnv()
    hostname = cgiEnv.GetId()

    nodeHost = lib_common.gUriGen.HostnameUri(hostname)

    grph = cgiEnv.GetGraph()

    # Return the name of the computer, name of the user, and active and idle times for the session.
    # No special group membership is required for level 0 or level 10 calls.
    level = 10

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

        sessionList = win32net.NetSessionEnum(level, hostname)
    except Exception:
        lib_common.ErrorMessageHtml("Hostname=" + hostname + ". Exception:" +
                                    str(sys.exc_info()))

    for eltLst in sessionList:
        for keyLst in eltLst:
            valLst = eltLst[keyLst]
            grph.add((nodeHost, lib_common.MakeProp(keyLst),
                      lib_common.NodeLiteral(valLst)))

    cgiEnv.OutCgiRdf()
Exemple #22
0
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    # subscriptionName=Azure.DefaultSubscription()
    subscriptionName = cgiEnv.m_entity_id_dict["Subscription"]

    (subscription_id, certificate_path) = lib_credentials.GetCredentials(
        "Azure", subscriptionName)

    sms = ServiceManagementService(subscription_id, certificate_path)

    subscriptionNode = subscription.MakeUri(subscriptionName)

    try:
        # This throws when running with Apache. OK with cgiserver.py
        lstLocations = sms.list_locations()
    except:
        lib_common.ErrorMessageHtml("Unexpected error:" + str(sys.exc_info()))

    result = lstLocations
    for loca in result:
        locaNode = location.MakeUri(loca.name, subscriptionName)

        grph.add((subscriptionNode, lib_common.MakeProp("Location"), locaNode))

    cgiEnv.OutCgiRdf()
Exemple #23
0
def AddNodesTablesViews(grph, fil_node, db_fil_nam):

    # This is imported here to avoid circular references of packages including themselves.
    from sources_types.sqlite import table as sqlite_table
    from sources_types.sqlite import view as sqlite_view

    logging.debug("db_fil_nam=%s", db_fil_nam)
    try:
        con = sqlite3.connect(db_fil_nam)
        cursor = con.cursor()
        # type TEXT,
        # name TEXT,
        # tbl_name TEXT,
        # rootpage INTEGER,
        # sql TEXT
        cursor.execute(
            "SELECT * FROM sqlite_master WHERE type='table' or type='view';")

        #[(u'table', u'tz_schema_version', u'tz_schema_version', 2, u'CREATE TABLE tz_schema_version (version INTEGER)'),

        for the_row in cursor.fetchall():
            the_type = the_row[0]
            the_name = the_row[1]
            if the_type == 'table':
                name_nod = sqlite_table.MakeUri(db_fil_nam, the_name)
                grph.add((fil_node, lib_common.MakeProp("Table"), name_nod))
            elif the_type == 'view':
                name_nod = sqlite_view.MakeUri(db_fil_nam, the_name)
                grph.add((fil_node, lib_common.MakeProp("View"), name_nod))
            else:
                continue

            the_rootpage = the_row[3]
            grph.add((name_nod, lib_common.MakeProp("Root page"),
                      lib_util.NodeLiteral(the_rootpage)))
            grph.add((name_nod, lib_common.MakeProp("Type"),
                      lib_util.NodeLiteral(the_type)))

            # Do not print too much information in case there are too many tables.
            #theCmd = the_row[4]
            #grph.add( ( tabNod, pc.property_information, lib_util.NodeLiteral(theCmd) ) )
    except sqlite3.DatabaseError as exc:
        lib_common.ErrorMessageHtml("Sqlite file:%s Caught:%s" %
                                    (db_fil_nam, str(exc)))
    except Exception as exc:
        lib_common.ErrorMessageHtml("Sqlite file:%s Unexpected error:%s" %
                                    (db_fil_nam, str(exc)))
Exemple #24
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    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()
    try:
        #
        listQueues = cl.get_queues()
    except:
        #
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for quList in listQueues:
        namQueue = quList["name"]
        DEBUG("q=%s", namQueue)

        namVHost = quList["vhost"]
        nodVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)

        nodeQueue = survol_rabbitmq_queue.MakeUri(configNam, namVHost,
                                                  namQueue)

        grph.add((nodeQueue, lib_common.MakeProp("vhost"),
                  lib_common.NodeLiteral(namVHost)))
        grph.add((nodeQueue, lib_common.MakeProp("vhost node"), nodVHost))

        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "queues",
                                                     namVHost, namQueue)

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

        grph.add((nodeManager, lib_common.MakeProp("Queue"), nodeQueue))

    cgiEnv.OutCgiRdf()
Exemple #25
0
def AddInfo(grph, node, entity_ids_arr):
    nam_config = entity_ids_arr[0]

    node_manager = survol_rabbitmq_manager.MakeUri(nam_config)

    # Inverted property for nicer display.
    grph.add(
        (node, lib_common.MakeProp("Configuration manager"), node_manager))
Exemple #26
0
def AddNodesIpConfig(grph, rootNode, mapIpconfigs):

    prpNetAdapt = lib_common.MakeProp("Network adapter")
    for keyMap in mapIpconfigs:
        subMapIpconfigs = mapIpconfigs[keyMap]
        naNode = AddOneNodeIpConfig(grph, rootNode, keyMap, subMapIpconfigs)
        if naNode:
            grph.add((rootNode, prpNetAdapt, naNode))
Exemple #27
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    configNam = cgiEnv.m_entity_id_dict["Url"]
    # namVHost = cgiEnv.m_entity_id_dict["VHost"]

    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()

    try:
        #
        listExchanges = cl.get_exchanges()
    except:
        #
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for objExchange in listExchanges:
        namExchange = objExchange["name"]
        DEBUG("namExchange=%s", namExchange)

        namVHost = objExchange["vhost"]
        nodeExchange = survol_rabbitmq_exchange.MakeUri(
            configNam, namVHost, namExchange)

        nodVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)
        grph.add(
            (nodeExchange, lib_common.MakeProp("virtual host node"), nodVHost))

        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "exchanges",
                                                     namVHost, namExchange)

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

        grph.add((nodVHost, lib_common.MakeProp("Exchange"), nodeExchange))

    cgiEnv.OutCgiRdf()
Exemple #28
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])
Exemple #29
0
def AddInfo(grph, node, entity_ids_arr):
    # TODO: SPECIAL. Imported here to avoid circular inclusions, see oracle/package_body/__init__.py
    from sources_types.oracle import schema as oracle_schema

    argDb = entity_ids_arr[0]
    argSchema = entity_ids_arr[1]

    node_oraschema = oracle_schema.MakeUri(argDb, argSchema)
    grph.add((node_oraschema, lib_common.MakeProp("Oracle synonym"), node))
Exemple #30
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()