def Main(): formAction = os.environ['SCRIPT_NAME'] cgiArguments = cgi.FieldStorage() credFilename = os.path.normpath(lib_credentials.credentials_filename()) page_title = "Edit Survol credentials in %s" % credFilename # Hostname=Unknown-30-b5-c2-02-0c-b5-2.home # Host address=192.168.0.17 # Remote client=82.45.12.63 currHostNam = socket.gethostname() currHostAddr = lib_util.GlobalGetHostByName(currHostNam) try: addrRemote = os.environ['REMOTE_ADDR'] except KeyError: #ERROR("edit_credentials.py: Cannot get REMOTE_ADDR") sys.stderr.write("edit_credentials.py: Cannot get REMOTE_ADDR\n") raise if addrRemote not in ["82.45.12.63","192.168.0.14","127.0.0.1"]: lib_common.ErrorMessageHtml("Access forbidden from %s"% addrRemote ) InsertedCredMap(cgiArguments) credMap = UpdatedCredMap(cgiArguments) credTypesWellKnown = CredDefinitions() credTypeList=sorted(credTypesWellKnown.keys()) if lib_util.GetJinja2(): MainJinja(page_title,currHostNam,currHostAddr,addrRemote,credMap,formAction,credTypeList) else: MainNoJinja(page_title,currHostNam,currHostAddr,addrRemote,credMap,formAction,credTypeList)
def Main(): cgiEnv = lib_common.CgiEnv() try: thePid = int(cgiEnv.GetId()) except Exception: lib_common.ErrorMessageHtml("Must provide a pid") grph = cgiEnv.GetGraph() proc_obj = CIM_Process.PsutilGetProcObj(thePid) node_process = lib_common.gUriGen.PidUri(thePid) CIM_Process.AddInfo(grph, node_process, [str(thePid)]) filCGroups = "/proc/%d/cgroup" % thePid for lin_cg in open(filCGroups): split_cg = lin_cg.split(':') hierarchy = split_cg[0] subsys_name_list = split_cg[1] mount_path = split_cg[2] mount_path_node = lib_common.gUriGen.DirectoryUri(mount_path) for subsys_name in subsys_name_list.split(","): cgrpNode = survol_cgroup.MakeUri(subsys_name) grph.add((node_process, lib_common.MakeProp("CGroup"), cgrpNode)) grph.add((cgrpNode, lib_common.MakeProp("Hierarchy"), lib_common.NodeLiteral(hierarchy))) grph.add((cgrpNode, lib_common.MakeProp("Control group path"), mount_path_node)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment() table_name = cgiEnv.m_entity_id_dict["Table"] db_fil_nam = cgiEnv.m_entity_id_dict["File"] grph = cgiEnv.GetGraph() fil_node = lib_uris.gUriGen.FileUri(db_fil_nam) tab_nod = sqlite_table.MakeUri(db_fil_nam, table_name) grph.add((tab_nod, lib_common.MakeProp("Table"), fil_node)) con = sqlite3.connect(db_fil_nam) cursor = con.cursor() #>>> eta = curs.execute("PRAGMA table_info('tz_data')") #(0, u'tzid', u'TEXT', 0, None, 0) #(1, u'alias', u'TEXT', 0, None, 0) try: cursor.execute("PRAGMA table_info('%s')" % table_name) prop_column = lib_common.MakeProp("Column") prop_type = lib_common.MakeProp("Type") for the_row in cursor.fetchall(): column_nam = the_row[1] column_nod = sqlite_column.MakeUri(db_fil_nam, table_name, column_nam) grph.add((tab_nod, prop_column, column_nod)) type_nam = the_row[2] grph.add((column_nod, prop_type, lib_util.NodeLiteral(type_nam))) except Exception as exc: lib_common.ErrorMessageHtml("Error %s:%s" % (db_fil_nam, str(exc))) cgiEnv.OutCgiRdf("LAYOUT_RECT", [prop_column])
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() lib_common.ErrorMessageHtml("Not implemented yet") cgiEnv.OutCgiRdf("LAYOUT_RECT")
def Main(): cgiEnv = lib_common.ScriptEnvironment() pid = int(cgiEnv.GetId()) grph = cgiEnv.GetGraph() proc_obj = CIM_Process.PsutilGetProcObj(pid) node_process = lib_uris.gUriGen.PidUri(pid) try: all_maps = proc_obj.memory_maps() except Exception as exc: lib_common.ErrorMessageHtml("get_memory_maps Pid=%d. Caught %s\n" % (pid, str(exc))) propMemoryRSS = lib_common.MakeProp("Resident Set Size") for map_obj in all_maps: # This, because all Windows paths are "standardized" by us. # TODO: clean_map_path = lib_util.standardized_file_path(map_obj.path) clean_map_path = map_obj.path.replace("\\", "/") uri_mem_map = lib_uris.gUriGen.MemMapUri(clean_map_path) grph.add((uri_mem_map, propMemoryRSS, rdflib.Literal(map_obj.rss))) grph.add((node_process, pc.property_memmap, uri_mem_map)) cgiEnv.OutCgiRdf( "LAYOUT_SPLINE")
def Main(): cgiEnv = lib_oracle.OracleEnv() grph = cgiEnv.GetGraph() database = cgiEnv.m_oraDatabase ora_user, ora_pwd = lib_credentials.GetCredentials("Oracle", database) conn_str = ora_user + "/" + ora_pwd + "@" + database # The Oracle user needs: grant select any dictionary to <user>; qry_select = """ SELECT sess.status, sess.username, sess.schemaname, sql.sql_text,sql.sql_fulltext,proc.spid FROM v$session sess, v$sql sql, v$process proc WHERE sql.sql_id(+) = sess.sql_id AND sess.type = 'USER' and sess.paddr = proc.addr """ prop_sql_query = lib_common.MakeProp("SQL query") ora_parser = OraCallbackParseQry(grph, database, prop_sql_query) # This calls the callback for each retrieved row. try: lib_oracle.CallbackQuery(conn_str, qry_select, ora_parser.oracallback) except Exception as exc: lib_common.ErrorMessageHtml("CallbackQuery exception:%s in %s" % (str(exc), qry_select)) cgiEnv.OutCgiRdf("LAYOUT_RECT", [prop_sql_query])
def AddInfoFromImport(grph, packageNode, packageKey): try: the_module = importlib.import_module(packageKey) except ImportError: lib_common.ErrorMessageHtml("Importing %s: Error %s" % (packageKey, str(sys.exc_info()))) try: initFilNam = the_module.__file__ filNode = lib_common.gUriGen.FileUri(initFilNam) grph.add((packageNode, propPythonPackage, filNode)) except AttributeError: pass try: txtDoc = the_module.__doc__ if txtDoc: grph.add((packageNode, pc.property_information, lib_common.NodeLiteral(txtDoc))) except AttributeError: pass propsPackage = {"Author": "__author__", "Version": "__version__"} for keyProp in propsPackage: valProp = propsPackage[keyProp] try: txtVal = getattr(the_module, valProp) if txtVal: grph.add((packageNode, lib_common.MakeProp(keyProp), lib_common.NodeLiteral(txtVal))) except AttributeError: pass
def FeederCreateOrGet(self, entityId): self.LogMsg("Checking to create feeder entity=" + entityId) try: pidFeeder = self.m_feeder[entityId].pid if psutil.pid_exists(pidFeeder): self.LogMsg("Feeder is running as expected: entity=" + entityId + " pid=" + str(pidFeeder)) else: msg = "Feeder should be running: entity=" + entityId + " pid=" + str( pidFeeder) self.LogMsg(msg) lib_common.ErrorMessageHtml(msg) # TODO: WE COULD ATTEMPT TO RESTART THE FEEDER PROCESS. except KeyError: self.LogMsg("Actually creating feeder entity=" + entityId) theQ = multiprocessing.Queue() # BEWARE: Should put a lock here, because dict() is not thread safe !! self.m_queues[entityId] = theQ the_feeder = Feeder(self.m_engine, entityId, theQ) self.m_feeder[entityId] = the_feeder self.LogMsg("About to start feeder entity=" + entityId) the_feeder.start() # Give it a bit of time to start properly, but this is not essential. # TODO: Maybe remove this in the future. # Rather, for example should wait until the port number is used. time.sleep(1) self.LogMsg("Created feeder entity=" + entityId + " pid=" + str(the_feeder.pid))
def __init__(self, PortNum, DataEngine, Deserializer, Title, layoutParams, logFileName): try: self.m_logFileName = logFileName self.m_logFd = open(self.m_logFileName, "a") self.LogMsg("RdfStreamServer ctor:PortNum=" + str(PortNum) + " log=" + logFileName) self.m_pid = os.getpid() self.m_feeder = dict() self.m_engine = DataEngine self.m_queues = dict() self.m_deserial = Deserializer self.m_page_title = Title self.m_dot_layout = layoutParams # Start HTTP server server_address = ('127.0.0.1', PortNum) super(RdfStreamServer, self).__init__(server_address, RdfQueue_HTTPRequestHandler) self.LogMsg("RdfStreamServer started") HTTPServer.serve_forever(self) except Exception: exc = sys.exc_info()[1] self.LogMsg("Caught when creating RdfStreamServer:" + str(exc)) lib_common.ErrorMessageHtml("From RDFStreamServer ctor, caught:" + str(exc))
def DisplayAsMime(grph,node,entity_ids_arr): fileName = entity_ids_arr[0] groupName = entity_ids_arr[1] DEBUG("fileName=%s groupName=%s", fileName, groupName ) # Using LoadLibrary (rather than CreateFile) is required otherwise # LoadResource, FindResource and others will fail hlib = win32api.LoadLibraryEx(fileName, 0, 2) DEBUG("fileName=%s groupName=%s",fileName,str(groupName)) try: groupName = int(groupName) except: pass # The destructor will remove the temporary file. objTempFile = IconToFile(hlib,groupName) rsrcFilNam = objTempFile.Name try: lib_util.CopyFile( mimeTypeResource, rsrcFilNam ) except Exception: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("DisplayAsMime rsrcFilNam=%s, mime_type=%s caught:%s" % ( rsrcFilNam, mime_type, str(exc) ) )
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()
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()
def Main(): cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True) cimom_url = cgiEnv.GetHost() grph = cgiEnv.GetGraph() # There is no consensus on the WBEM class for namespaces, # so we have ours which must be correctly mapped. namespace_class = "wbem_namespace" root_node = lib_util.EntityUri(namespace_class, "") try: conn_wbem = lib_wbem.WbemConnection(cimom_url) nsd = lib_wbem.EnumNamespacesCapabilities(conn_wbem) except Exception as exc: lib_common.ErrorMessageHtml("Namespaces from :" + cimom_url + " Caught:" + str(exc)) # TODO: We should draw a namespaces tree but more examples needed. for nskey in nsd: cnt = nsd[nskey] wbem_url = lib_wbem.NamespaceUrl(nskey, cimom_url) wbem_node = lib_common.NodeUrl(wbem_url) grph.add((root_node, pc.property_cim_subnamespace, wbem_node)) grph.add( (wbem_node, pc.property_information, lib_util.NodeLiteral(nskey))) grph.add( (wbem_node, pc.property_information, lib_util.NodeLiteral(cnt))) cgiEnv.OutCgiRdf("LAYOUT_RECT")
def CheckWindowsModule(win_module): if not lib_util.isPlatformWindows: lib_common.ErrorMessageHtml("DLL files are on Windows platforms only") if os.path.isdir(win_module): lib_common.ErrorMessageHtml("File '" + win_module + "' must be a plain file") if not os.path.isfile(win_module): lib_common.ErrorMessageHtml("File '" + win_module + "' does not exist") filename, file_extension = os.path.splitext(win_module) if not file_extension.upper() in ('.EXE', '.DLL'): lib_common.ErrorMessageHtml( "File '" + win_module + "' should be a Windows module. Extension=" + file_extension)
def ExecuteQuery(conn_str, sql_query): try: return ExecuteQueryThrow(conn_str, sql_query) except cx_Oracle.DatabaseError: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("ExecuteQuery exception:%s in %s" % (str(exc), sql_query))
def SetRunning(self): GblLog("SetRunning getpid=%d pid=%d port=%d" % (os.getpid(), self.m_pidSubSrv, self.m_PortNumber)) if self.m_isSubSrv: lib_common.ErrorMessageHtml("Already running pid=%d port=%d\n" % (self.m_pidSubSrv, self.m_PortNumber)) # File is not there. Possible race condition. self.m_logFd = open(self.m_logFilNam, "w+") # If we could open it, now write the port number so it can be read by the others. # Must immediately allocate a socket. self.m_PortNumber = portDict[self.m_appBaseName] self.m_pidSubSrv = os.getpid() # Atomic write. self.m_logFd.write("%d %d\n" % (self.m_pidSubSrv, self.m_PortNumber)) # Checks that it is properly written. self.m_logFd.seek(0) linSplit = self.m_logFd.readline().split(" ") pidSubSrvAlt = int(linSplit[0]) PortNumberAlt = int(linSplit[1]) if (self.m_pidSubSrv != pidSubSrvAlt) or (self.m_PortNumber != PortNumberAlt): # Race condition. Another process is faster than us. self.m_pidSubSrv = pidSubSrvAlt self.m_PortNumber = PortNumberAlt self.m_isSubSrv = False self.m_logFd.close() GblLog("Race condition %d %d" % (self.m_pidSubSrv, self.m_PortNumber)) return False self.m_isSubSrv = True return True
def Main(): cgiEnv = lib_common.ScriptEnvironment() 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_uris.gUriGen.PidUri(procId) grph.add( ( cgroupNode, propCGroup, procNode ) ) except: logging.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(): cgiEnv = lib_common.ScriptEnvironment() file_shared_lib = cgiEnv.GetId() if not lib_util.isPlatformLinux: lib_common.ErrorMessageHtml("LDD on Linux platform only") grph = cgiEnv.GetGraph() # Maybe the file does not contain its path so it must be added. if file_shared_lib[0] != '/': file_shared_lib = os.getcwd() + '/' + file_shared_lib node_shared_lib = lib_uris.gUriGen.SharedLibUri(file_shared_lib) CIM_DataFile.AddInfo(grph, node_shared_lib, [file_shared_lib]) stream = os.popen("ldd " + file_shared_lib) # Line read are such as: # linux-gate.so.1 => (0xffffe000) # libdl.so.2 => /lib/libdl.so.2 (0xb7dae000) # libc.so.6 => /lib/i686/libc.so.6 (0xb7c6a000) # /lib/ld-linux.so.2 (0x80000000) # Do not know what to do with the lines without an arrow. # Do not know what happens if a library name contains a space. rgx = re.compile(r'^.*=> *([^ ]+) \(') for line in stream: match_obj = re.match(rgx, line) if match_obj: AddDepends(grph, node_shared_lib, match_obj.group(1)) # The dependencies are flattened which may be is a mistake. cgiEnv.OutCgiRdf("LAYOUT_RECT")
def Main(): cgiEnv = lib_common.ScriptEnvironment() configNam = cgiEnv.GetId() nodeManager = survol_rabbitmq_manager.MakeUri(configNam) creds = lib_credentials.GetCredentials("RabbitMQ", configNam) # cl = Client('localhost:12345', 'guest', 'guest') cl = Client(configNam, creds[0], creds[1]) grph = cgiEnv.GetGraph() try: lstOverview = cl.get_overview() except Exception as exc: lib_common.ErrorMessageHtml("Caught:" + str(exc)) for keyOverview in lstOverview: valOverview = lstOverview[keyOverview] valClean = valOverview # Otherwise it does not work as these chars should be espaced. # TODO: Nice display for Python lists and dicts. valClean = str(valClean).replace("{", "").replace("}", "") grph.add((nodeManager, lib_common.MakeProp(keyOverview), lib_util.NodeLiteral(valClean))) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() # [suser(name='Remi', terminal=None, host='0.246.33.0', started=1411052436.0)] try: # Windows XP, Python 3. try: # Windows XP, Python 3.4. users_list = psutil.users() except AttributeError: # Linux and Python 2.5 # Windows 7, Python 3.2 : mais c'est la version de psutil qui compte. users_list = psutil.get_users() except AttributeError: # AttributeError: 'module' object has no attribute 'users' lib_common.ErrorMessageHtml("Function users() not available") for user in users_list: usrNam = lib_common.format_username(user.name) userNode = lib_common.gUriGen.UserUri(usrNam) grph.add((lib_common.nodeMachine, pc.property_user, userNode)) cgiEnv.OutCgiRdf()
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()
def GetInfoStat(file_name): try: info = os.stat(file_name) except Exception as exc: # On recent Python versions, we would catch IOError or FileNotFoundError. lib_common.ErrorMessageHtml("Caught:" + str(exc)) except IOError: lib_common.ErrorMessageHtml("IOError:" + file_name) except FileNotFoundError: lib_common.ErrorMessageHtml("File not found:" + file_name) except PermissionError: lib_common.ErrorMessageHtml("Permission error:" + file_name) except OSError: lib_common.ErrorMessageHtml("Incorrect syntax:" + file_name) return info
def Main(): cgiEnv = lib_common.ScriptEnvironment() config_nam = cgiEnv.m_entity_id_dict["Url"] nam_connection = cgiEnv.m_entity_id_dict["Connection"] node_manager = survol_rabbitmq_manager.MakeUri(config_nam) creds = lib_credentials.GetCredentials("RabbitMQ", config_nam) cl = Client(config_nam, creds[0], creds[1]) grph = cgiEnv.GetGraph() logging.debug("nam_connection=%s", nam_connection) nod_connection = survol_rabbitmq_connection.MakeUri(config_nam, nam_connection) grph.add((node_manager, lib_common.MakeProp("Connection"), nod_connection)) try: connect_list = cl.get_connection(nam_connection) except Exception as exc: lib_common.ErrorMessageHtml("Caught:" + str(exc)) for connect_key in connect_list: connect_val = connect_list[connect_key] if connect_key == "vhost": nod_v_host = survol_rabbitmq_vhost.MakeUri(config_nam, connect_val) grph.add((nod_connection, lib_common.MakeProp("Virtual host"), nod_v_host)) elif connect_key == "user": nod_user = survol_rabbitmq_user.MakeUri(config_nam, connect_val) grph.add((nod_connection, lib_common.MakeProp("User"), nod_user)) elif connect_key == "host": nod_host = lib_uris.gUriGen.HostnameUri(connect_val) grph.add((nod_connection, lib_common.MakeProp("Host"), nod_host)) elif connect_key in ["name", "peer_host", "peer_port"]: pass else: if isinstance(connect_val, six.string_types): connect_val = connect_val.replace(">", "@") logging.debug("connect_key=%s connect_val=%s", connect_key, connect_val) elif isinstance(connect_val, dict): pass elif isinstance(connect_val, tuple): pass elif isinstance(connect_val, list): pass else: pass logging.debug("Literal=%s", lib_util.NodeLiteral(connect_val)) grph.add((nod_connection, lib_common.MakeProp(connect_key), lib_util.NodeLiteral(connect_val))) survol_rabbitmq_connection.AddSockets(grph, nod_connection, nam_connection) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True) entity_host = cgiEnv.GetHost() logging.debug("entity_host=%s", entity_host) entity_host = lib_wmi.NormalHostName(entity_host) cimom_url = entity_host logging.debug("cimom_url=%s", cimom_url) grph = cgiEnv.GetGraph() # There is no consensus on the WMI class for namespaces, # so we have ours which must be correctly mapped. namespace_class = "wmi_namespace" # root_node = lib_util.EntityUri(namespace_class,"") root_node = lib_util.EntityUri(namespace_class) for nskey in _hardcoded_namespaces: # _sub_namespace( root_node, grph, nskey ) try: # "root\\" + # _sub_namespace( root_node, grph, nskey, cimom_url ) _sub_namespace(root_node, grph, nskey, cimom_url) except Exception as exc: lib_common.ErrorMessageHtml("namespaces_wmi.py cimom_url=%s nskey=%s Caught:%s" % ( cimom_url, nskey , str(exc) ) ) cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_cim_subnamespace])
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])
def Main(): cgiEnv = lib_common.CgiEnv() pid = int(cgiEnv.GetId()) grph = cgiEnv.GetGraph() proc_obj = CIM_Process.PsutilGetProcObj(pid) #[pconn(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED'), # pconn(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING'), # pconn(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED'), node_process = lib_common.gUriGen.PidUri(pid) try: connects = CIM_Process.PsutilProcConnections(proc_obj, 'all') except Exception: # Version 3.2.2 at least. try: connects = proc_obj.connections('all') except Exception: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("Error:" + str(exc)) survol_addr.PsutilAddSocketToGraph(node_process, connects, grph) cgiEnv.OutCgiRdf()
def EnumServices(grph, subscriptionName): (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 lstSrvs = sms.list_hosted_services() except: lib_common.ErrorMessageHtml("Unexpected error:" + str(sys.exc_info())) for srv in lstSrvs: servNode = service.MakeUri(srv.service_name, subscriptionName) grph.add((subscriptionNode, lib_common.MakeProp("Service"), servNode)) # There will be duplicates. locaNode = location.MakeUri(srv.hosted_service_properties.location, subscriptionName) grph.add((servNode, lib_common.MakeProp("Location"), locaNode)) grph.add((servNode, pc.property_rdf_data_nolist1, lib_common.NodeUrl(srv.url)))
def Main(): cgiEnv = lib_common.CgiEnv() hostname = cgiEnv.GetId() nodeHost = lib_common.gUriGen.HostnameUri(hostname) grph = cgiEnv.GetGraph() # Loop over the shares. shareresume = 0 while 1: try: # 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(hostname): hostname_or_None = None level = 2 # 1,2 else: hostname_or_None = hostname level = 1 # 1,2 sharedata, total, shareresume = win32net.NetShareEnum( hostname_or_None, level, shareresume) except Exception: # "Access is denied." exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("Hostname=" + hostname + ". Exception:" + str(exc)) for share in sharedata: DEBUG("share=%s", str(share)) # share={'remark': 'Remote Admin', 'passwd': None, 'current_uses': 0, 'netname': 'ADMIN$', 'max_uses': 4294967295, 'path': 'C:\\\\Windows', 'type': 2147483648, 'permissions': 0} share_netname = share['netname'] try: share_path = share['path'] share_remark = share['remark'] except: share_path = "" share_remark = "" shareNode = lib_common.gUriGen.SmbShareUri("//" + hostname + "/" + share_netname) grph.add((nodeHost, pc.property_smbshare, shareNode)) if share_path: # TODO: Horrible display. Strange because this is encoded in the function. # mountNode = lib_common.gUriGen.FileUri( share_path.replace('\\','/') ) mountNode = lib_common.gUriGen.FileUri(share_path) grph.add((shareNode, pc.property_smbmount, mountNode)) if share_remark: grph.add((shareNode, pc.property_information, lib_common.NodeLiteral(share_remark))) if not shareresume: break cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() # List xml config files in the directory given by the environment variable "XCOMP_AC2_BASE" which by default is "C:\AC2" envVarNam = "XCOMP_AC2_BASE" try: ac2TopDir = os.environ[envVarNam] except: lib_common.ErrorMessageHtml( "Cannot get environment variable value %s" % envVarNam) # Directory on Windows. nodeTopDir = lib_common.gUriGen.DirectoryUri( ac2TopDir.replace("\\", "/") + "/confs") rootNode = lib_common.nodeMachine grph.add((rootNode, lib_common.MakeProp("Machine"), nodeTopDir)) for root, dirs, files in os.walk(ac2TopDir): for file in files: if file.endswith(".xml"): fullFileName = os.path.join(root, file) nodeConfig = lib_common.gUriGen.UriMakeFromDict( "AC2/configuration", {"File": fullFileName}) grph.add((nodeTopDir, lib_common.MakeProp("AC2 configuration"), nodeConfig)) cgiEnv.OutCgiRdf()