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()
def WmiConnect(machWithBackSlashes, wmiNamspac, throw_if_error=True): sys.stderr.write("WmiConnect cimom=%s wmiNamspace=%s\n" % (machWithBackSlashes, wmiNamspac)) # WmiConnect cimom=\\\\rchateau-HP\\:. wmiNamspace=aspnet if not machWithBackSlashes or lib_util.IsLocalAddress(machWithBackSlashes): sys.stderr.write("WmiConnect Local connect\n") # return wmi.WMI() return wmi.WMI(find_classes=False) wmiMachine, wmiUser, wmiPass = GetWmiUserPass(machWithBackSlashes) #wmiMachineIpAddr = socket.gethostbyaddr(wmiMachine) #sys.stderr.write("WmiConnect wmiMachine=%s wmiMachineIpAddr=%s wmiUser=%s wmiPass=%s\n" % ( wmiMachine,wmiMachineIpAddr,wmiUser,wmiPass ) ) dictParams = {} if wmiNamspac: dictParams['namespace'] = wmiNamspac if wmiUser: dictParams['user'] = wmiUser dictParams['password'] = wmiPass # TODO: THIS DOES NOT MAKE SENSE AND SHOULD BE CHANGED LIKE lib_wbem.py. if not lib_util.SameHostOrLocal(wmiMachine, None): dictParams['computer'] = wmiMachine sys.stderr.write("WmiConnect wmiMachine=%s wmiNamspac=%s dictParams=%s\n" % (wmiMachine, wmiNamspac, str(dictParams))) try: connWMI = wmi.WMI(**dictParams) #sys.stderr.write("WmiConnect after connection\n" ) except: dictParams['password'] = "******" # Security. if throw_if_error: # Could not connect, maybe the namespace is wrong. lib_common.ErrorMessageHtml( "WmiConnect Cannot connect to WMI server with params:%s.Exc=%s" % (str(dictParams), str(sys.exc_info()))) else: sys.stderr.write( "WmiConnect Cannot connect to WMI server with params:%s.Exc=%s\n" % (str(dictParams), str(sys.exc_info()))) return None #sys.stderr.write("WmiConnect returning\n" ) return connWMI
def KnownScriptToTitle(filScript, uriMode, entity_host=None, entity_suffix=None): # Extra information depending on the script. # Special display if MIME URL if filScript == "entity_mime.py": if not entity_suffix: entity_suffix = "None" # The Mime type is embedded into the mode, after a "mime:" prefix. entity_label = entity_suffix + " (" + lib_mime.ModeToMimeType( uriMode) + ")" return entity_label # The label is a Survol module name which is a class (With an EntityOntology() function), # or a namespace. So we give the right title. if filScript == "class_type_all.py": moduOntology = lib_util.OntologyClassKeys(entity_suffix) if moduOntology: entity_label = entity_suffix + " (Class)" else: entity_label = entity_suffix + " (Domain)" return entity_label try: entity_label = scripts_to_titles[filScript] except KeyError: entity_label = filScript + "..." if entity_suffix: if entity_label: entity_label = entity_suffix + " (" + entity_label + ")" else: entity_label = entity_suffix # Maybe hostname is a CIMOM address (For WBEM) or a machine name. if entity_host: if not lib_util.IsLocalAddress(entity_host): # If this is a CIMOM, make it shorter: "http://vps516494.ovh.net:5988" or ""https://vps516494.ovh.net:5989" host_only = lib_util.EntHostToIp(entity_host) entity_label += " at " + host_only # TODO: Add the host name in the title. return entity_label
def CalcLabel(entity_host, entity_type, entity_id, force_entity_ip_addr, filScript): namSpac, entity_type_NoNS = lib_util.parse_namespace_type(entity_type) if not force_entity_ip_addr and not lib_util.IsLocalAddress(entity_host): entity_label = None if filScript == "entity_wbem.py": import lib_wbem # Because of WBEM, entity_host is a CIMOM url, like "http://vps516494.ovh.net:5988" entity_label = lib_wbem.EntityToLabelWbem(namSpac, entity_type_NoNS, entity_id, entity_host) if not entity_label: # Fallback to Survol label. actual_host = lib_util.EntHostToIp(entity_host) entity_label = EntityToLabel(entity_type_NoNS, entity_id, actual_host) elif filScript == "entity_wmi.py": import lib_wmi # For WMI, the hostname is a NETBIOS machine name. entity_label = lib_wmi.EntityToLabelWmi(namSpac, entity_type_NoNS, entity_id, entity_host) if not entity_label: # Fallback to Survol label. actual_host = lib_util.EntHostToIp(entity_host) entity_label = EntityToLabel(entity_type_NoNS, entity_id, actual_host) else: # filScript in [ "class_type_all.py", "entity.py" ], or if no result from WMI or WBEM. entity_label = EntityToLabel(entity_type_NoNS, entity_id, entity_host) elif entity_type_NoNS or entity_id: entity_label = EntityToLabel(entity_type_NoNS, entity_id, force_entity_ip_addr) else: # Only possibility to print something meaningful. entity_label = namSpac # Some corner cases: "http://127.0.0.1/Survol/survol/entity.py?xid=CIM_ComputerSystem.Name=" if not entity_label: entity_label = entity_type return entity_label
def AddrUri(self, addr, port, transport="tcp"): try: portNam = socket.getservbyport(int(port)) except socket.error: portNam = str(port) # addr could be "LOCALHOST" if lib_util.IsLocalAddress(addr): # hostName, aliases, _ = socket.gethostbyaddr(hstAddr) # TODO: Should use the actual IP address. addr = "127.0.0.1" url = addr + ':' + portNam if transport != 'tcp': # This will happen rarely. url += ":" + transport # TODO: THIS IS WHERE WE SHOULD MAYBE ALWAYS USE A RemoteBox(). return self.UriMake("addr", url)
def AddrUri(self, addr, socketPort, transport="tcp"): # The standard id encodes the port as an integer. # But addr.EntityName() displays it with getservbyport try: socketPortNumber = socket.getservbyname(socketPort) except: socketPortNumber = int(socketPort) # addr could be "LOCALHOST" if lib_util.IsLocalAddress(addr): # hostName, aliases, _ = socket.gethostbyaddr(hstAddr) # TODO: Should use the actual IP address. addr = "127.0.0.1" url = "%s:%d" % (addr, socketPortNumber) if transport != 'tcp': # This will happen rarely. url += ":" + transport # TODO: THIS IS WHERE WE SHOULD MAYBE ALWAYS USE A RemoteBox(). return self.UriMake("addr", url)
def Main(): # This can process remote hosts because it does not call any script, just shows them. cgiEnv = lib_common.CgiEnv(can_process_remote=True, parameters={lib_util.paramkeyShowAll: False}) entity_id = cgiEnv.m_entity_id entity_host = cgiEnv.GetHost() flagShowAll = int(cgiEnv.get_parameters(lib_util.paramkeyShowAll)) nameSpace, entity_type = cgiEnv.get_namespace_type() if lib_util.IsLocalAddress(entity_host): entity_host = "" DEBUG("entity: entity_host=%s entity_type=%s entity_id=%s", entity_host, entity_type, entity_id) grph = cgiEnv.GetGraph() rootNode = lib_util.RootUri() if entity_id != "" or entity_type == "": entity_ids_arr = lib_util.EntityIdToArray(entity_type, entity_id) # TODO: Plutot qu'attacher tous les sous-directory a node parent, # ce serait peut-etre mieux d'avoir un seul lien, et d'afficher # les enfants dans une table, un record etc... # OU: Certaines proprietes arborescentes seraient representees en mettant # les objets dans des boites imbriquees: Tables ou records. # Ca peut marcher quand la propriete forme PAR CONSTRUCTION # un DAG (Direct Acyclic Graph) qui serait alors traite de facon specifique. def CallbackGrphAdd(tripl, depthCall): grph.add(tripl) DirToMenu(CallbackGrphAdd, rootNode, entity_type, entity_id, entity_host, flagShowAll) cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_directory, pc.property_script])
def MachineBox(mach): if lib_util.IsLocalAddress(mach): theMachineBox = LocalBox() else: theMachineBox = RemoteBox(mach) return theMachineBox
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()
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()