def _parseOutput(self, ipconfigBuffer, langBund):
     r'@types: str, ResourceBundle -> list[ip_addr._BaseIP]'
     keyword = langBund.getString('windows_ipconfig_str_dnsservers').strip()
     inDns = 0
     # order of added IPs is important so we do not use set and just check
     # for already added IPs
     ips = []
     parseIp = fptools.safeFunc(self.__parseIpInLine)
     if ipconfigBuffer:
         for line in ipconfigBuffer.splitlines():
             if (line.find(keyword) != -1):
                 inDns = 1
                 ip = parseIp(line)
                 if ip and not ip in ips and ip_addr.isValidIpAddressNotZero(
                         ip):
                     ips.append(ip)
                 continue
             if (inDns == 1):
                 if (line.find('. :') == -1):
                     ip = parseIp(line)
                     if ip and not ip in ips and ip_addr.isValidIpAddressNotZero(
                             ip):
                         ips.append(ip)
                 else:
                     inDns = 0
     return ips
Exemple #2
0
 def __getDnsServerIPs(self):
     '''
     @types: -> list[str]
     @raise Exception: WMI query failed
     '''
     ips = []
     clazz = 'Win32_NetworkAdapterConfiguration'
     queryBuilder = self._wmiProvider.getBuilder(clazz)
     queryBuilder.addWmiObjectProperties('dnsServerSearchOrder')
     queryBuilder.addWhereClause('domainDnsRegistrationEnabled <> NULL')
     agent = self._wmiProvider.getAgent()
     dnsServersConfigurationList = agent.getWmiData(queryBuilder)
     for dnsServersConfiguration in dnsServersConfigurationList:
         dnsIps = dnsServersConfiguration.dnsServerSearchOrder
         # depending on protocol this field represented as CSV string
         # or list of values
         if not isinstance(dnsIps, types.ListType):
             dnsIps = map(string.strip, str(dnsIps).split(','))
         for ip in dnsIps:
             if ip:
                 try:
                     if ip_addr.isValidIpAddressNotZero(ip):
                         ips.append(ip_addr.IPAddress(ip))
                 except:
                     logger.warn('Failed to parse to IP value "%s"' % ip)
     return ips
Exemple #3
0
    def buildVm(self, server):
        vm = openstack.Vm()
        vm.referenced_project = server.getTenantId()
        vm.name = server.getName()
        vm.status = server.getStatus()
        vm.host_id = server.getHostId()
        vm.id = server.getId()
        image = server.getImage()
        if image:
            logger.debug("server.getImage():", image)
            vm.image = openstack.Image(image.getId())
        flavor = server.getFlavor()
        if flavor:
            logger.debug("server.getFlavor():", flavor)
            vm.flavor = openstack.Flavor(flavor.getId())
        getExtendedAttributes = server.getExtendedAttributes()
        vm.hypervisorHostName = getExtendedAttributes.get(
        ).getHypervisorHostName()

        addrs = server.getAddresses().values()
        for addr in addrs:
            ip = addr.getAddr()
            if ip and ip_addr.isValidIpAddressNotZero(ip):
                vm.ips.append(ip_addr.IPAddress(ip))
        return vm
 def __getDnsServerIPs(self):
     '''
     @types: -> list[str]
     @raise Exception: WMI query failed
     '''
     ips = []
     clazz = 'Win32_NetworkAdapterConfiguration'
     queryBuilder = self._wmiProvider.getBuilder(clazz)
     queryBuilder.addWmiObjectProperties('dnsServerSearchOrder')
     queryBuilder.addWhereClause('domainDnsRegistrationEnabled <> NULL')
     agent = self._wmiProvider.getAgent()
     dnsServersConfigurationList = agent.getWmiData(queryBuilder)
     for dnsServersConfiguration in dnsServersConfigurationList:
         dnsIps = dnsServersConfiguration.dnsServerSearchOrder
         # depending on protocol this field represented as CSV string
         # or list of values
         if not isinstance(dnsIps, types.ListType):
             dnsIps = map(string.strip, str(dnsIps).split(','))
         for ip in dnsIps:
             if ip:
                 try:
                     if ip_addr.isValidIpAddressNotZero(ip):
                         ips.append(ip_addr.IPAddress(ip))
                 except:
                     logger.warn('Failed to parse to IP value "%s"' % ip)
     return ips
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    connection = Framework.getProbeDatabaseConnection('common')
    
    for mac_preffix, vendor in THIN_CLIENT_MAC_TO_VENDOR_PAIRS.items():
        st = getPreparedStatement(connection, mac_preffix)
        rs = st.executeQuery()
        while (rs.next()):
            mac = rs.getString('mac_address')
            ip = rs.getString('ip_address')
            if ip_addr.isValidIpAddressNotZero(ip) and not DSM.isIpOutOfScope(ip) and DSM.isClientIp(ip): 
                ip_osh = build_client_ip_osh(ip, mac)
                node_osh = build_node_osh(mac, vendor)
                if ip_osh and node_osh:
                    link_osh = modeling.createLinkOSH('containment', node_osh, ip_osh)
                    interface_osh = modeling.createInterfaceOSH(mac, node_osh)
                    OSHVResult.add(ip_osh)
                    OSHVResult.add(node_osh)
                    OSHVResult.add(link_osh)
                    OSHVResult.add(interface_osh)
                else:
                    debug('Failed to create topology for ip %s , mac %s, vendor %s' % (ip, mac, vendor))
            else:
                debug('Skipping IP address %s since it is invalid or not assigned to any probe or not in client ip range. ' %  ip)
        rs.close()
        connection.close(st)
  
    connection.close()
    return OSHVResult
Exemple #6
0
 def reportHostFromEndpoint(self, endpoint):
     r'''@types: Endpoint -> ObjectStateHolder
     @raise ValueError: Endpoint is not specified
     @raise ValueError: Invalid IP address
     '''
     if not endpoint:
         raise ValueError("Endpoint is not specified")
     if not ip_addr.isValidIpAddressNotZero(endpoint.getAddress()):
         raise ValueError("Invalid IP address")
     exec("import modeling")
     return modeling.createHostOSH(str(endpoint.getAddress()))  # @UndefinedVariable
Exemple #7
0
 def reportHostFromEndpoint(self, endpoint):
     r'''@types: Endpoint -> ObjectStateHolder
     @raise ValueError: Endpoint is not specified
     @raise ValueError: Invalid IP address
     '''
     if not endpoint:
         raise ValueError("Endpoint is not specified")
     if not ip_addr.isValidIpAddressNotZero(endpoint.getAddress()):
         raise ValueError("Invalid IP address")
     exec("import modeling")
     return modeling.createHostOSH(str(
         endpoint.getAddress()))  # @UndefinedVariable
 def _parseOutput(self, ipconfigBuffer, langBund):
     ips = []
     dhcpServerIpPattern = langBund.getString("windows_ipconfig_dhcp_server").strip()
     if ipconfigBuffer:
         for line in ipconfigBuffer.split("\n"):
             ipAddrBuffer = re.match(dhcpServerIpPattern, line)
             if ipAddrBuffer:
                 try:
                     raw_ip = ipAddrBuffer.group(1).strip()
                     if ip_addr.isValidIpAddressNotZero(raw_ip):
                         ips.append(ip_addr.IPAddress(raw_ip))
                 except:
                     logger.debug("Failed to transform to IP value: %s" % ipAddrBuffer.group(1).strip())
     return ips
 def parseNatedNetworks(self, elems):
     result = []
     if not elems:
         return []
     for elem in elems:
         logger.debug(elem.meta_data)
         m = re.match('(\d+.\d+.\d+.\d+)\.(\d+.\d+.\d+.\d+)', elem.meta_data)
         if m:
             ip = m.group(1) 
             mask = m.group(2)
             if ip_addr.isValidIpAddressNotZero(ip):
                 network = firewall.NatedNetwork(ip, mask)
                 result.append(network)
     return result
 def parseNatedNetworks(self, elems):
     result = []
     if not elems:
         return []
     for elem in elems:
         logger.debug(elem.meta_data)
         m = re.match('(\d+.\d+.\d+.\d+)\.(\d+.\d+.\d+.\d+)',
                      elem.meta_data)
         if m:
             ip = m.group(1)
             mask = m.group(2)
             if ip_addr.isValidIpAddressNotZero(ip):
                 network = firewall.NatedNetwork(ip, mask)
                 result.append(network)
     return result
 def _parseOutput(self, ipconfigBuffer, langBund):
     winsPrimServerIpPattern = self.langBund.getString("windows_ipconfig_primary_wins_server").strip()
     winsSecServerIpPattern = self.langBund.getString("windows_ipconfig_secondary_wins_server").strip()
     ips = []
     if ipconfigBuffer:
         for line in ipconfigBuffer.split("\n"):
             ipAddrBuffer = re.match(winsPrimServerIpPattern, line) or re.match(winsSecServerIpPattern, line)
             if ipAddrBuffer:
                 try:
                     raw_ip = ipAddrBuffer.group(1).strip()
                     if ip_addr.isValidIpAddressNotZero(raw_ip):
                         ips.append(ip_addr.IPAddress(raw_ip))
                 except:
                     logger.debug("Failed to transform to IP object value %s" % ipAddrBuffer.group(1).strip())
     return ips
 def _parseOutput(self, ipconfigBuffer, langBund):
     r"@types: str, ResourceBundle -> list[ip_addr._BaseIP]"
     keyword = langBund.getString("windows_ipconfig_str_dnsservers").strip()
     inDns = 0
     # order of added IPs is important so we do not use set and just check
     # for already added IPs
     ips = []
     parseIp = fptools.safeFunc(self.__parseIpInLine)
     if ipconfigBuffer:
         for line in ipconfigBuffer.splitlines():
             if line.find(keyword) != -1:
                 inDns = 1
                 ip = parseIp(line)
                 if ip and not ip in ips and ip_addr.isValidIpAddressNotZero(ip):
                     ips.append(ip)
                 continue
             if inDns == 1:
                 if line.find(". :") == -1:
                     ip = parseIp(line)
                     if ip and not ip in ips and ip_addr.isValidIpAddressNotZero(ip):
                         ips.append(ip)
                 else:
                     inDns = 0
     return ips
 def _parseOutput(self, ipconfigBuffer, langBund):
     ips = []
     dhcpServerIpPattern = langBund.getString(
         'windows_ipconfig_dhcp_server').strip()
     if ipconfigBuffer:
         for line in ipconfigBuffer.split('\n'):
             ipAddrBuffer = re.match(dhcpServerIpPattern, line)
             if ipAddrBuffer:
                 try:
                     raw_ip = ipAddrBuffer.group(1).strip()
                     if ip_addr.isValidIpAddressNotZero(raw_ip):
                         ips.append(ip_addr.IPAddress(raw_ip))
                 except:
                     logger.debug('Failed to transform to IP value: %s' %
                                  ipAddrBuffer.group(1).strip())
     return ips
 def __getDhcpServerIpList(self):
     ''' -> list(str)
     @raise Exception: if WMI query failed
     '''
     ips = []
     queryBuilder = self._wmiProvider.getBuilder('Win32_NetworkAdapterConfiguration')
     queryBuilder.addWmiObjectProperties('dhcpServer')
     queryBuilder.addWhereClause('dhcpServer <> NULL')
     dhcpServerConfigurationList = self._wmiProvider.getAgent().getWmiData(queryBuilder)
     for dhcpServerConfiguration in dhcpServerConfigurationList:
         try:
             if ip_addr.isValidIpAddressNotZero(dhcpServerConfiguration.dhcpServer):
                 ips.append(ip_addr.IPAddress(dhcpServerConfiguration.dhcpServer))
         except:
             logger.debug('Failed to transform to IP object %s' % dhcpServerConfiguration.dhcpServer)
         return ips
 def __getWinsServerIpList(self):
     ''' -> list(str)
     @raise Exception: if WMI query failed
     '''
     ips = []
     queryBuilder = self._wmiProvider.getBuilder('Win32_NetworkAdapterConfiguration')
     queryBuilder.addWmiObjectProperties('WinsPrimaryServer', 'WinsSecondaryServer')
     queryBuilder.addWhereClause('WinsPrimaryServer <> NULL or WinsSecondaryServer <> NULL')
     winsServerConfigurationList = self._wmiProvider.getAgent().getWmiData(queryBuilder)
     for winsServerConfiguration in winsServerConfigurationList:
         for ip in [winsServerConfiguration.WinsPrimaryServer, winsServerConfiguration.WinsSecondaryServer]:
             try:
                 if ip_addr.isValidIpAddressNotZero(ip):
                     ips.append(ip_addr.IPAddress(ip))
             except:
                 logger.debug('Failed to transform to IP obj value %s' % ip)
     return ips
Exemple #16
0
    def _parseChassisData(self, output):
        result = []
        for chunk in re.split('[\r\n]{4}', output):
            if not (chunk and chunk.strip()):
                continue
            elems = parse_result_as_dict(chunk)
            chassis = ibm_fsm.Chassis()
            host_name = elems.get('Hostname', '')
            if not netutils.isValidIp(host_name):
                if host_name.find('.') == -1:
                    chassis.hostname = host_name
                else:
                    chassis.hostname = host_name[:host_name.find('.')]
            ips_raw = []
            ips_raw.extend([
                x.strip()
                for x in elems.get('ipv4', '').strip(' []').split(',')
                if x and x.strip()
            ])
            ips_raw.extend([
                x.strip()
                for x in elems.get('ipv6', '').strip(' []').split(',')
                if x and x.strip()
            ])
            for ip_str in ips_raw:
                if ip_str and ip_addr.isValidIpAddressNotZero(ip_str):
                    chassis.ipList.append(ip_addr.IPAddress(ip_str))

            if not (chassis.hostname or chassis.ipList):
                continue

            if elems.get('NetInterface'):
                chassis.iface.append(elems.get('NetInterface'))

            chassis.name = elems.get('Name')
            chassis.id = elems.get('Id')
            chassis.guid = elems.get('GUID')
            chassis.board_uuid = elems.get('System Board UUID')
            chassis.serial = elems.get('Serial Number')
            chassis.frim_level = elems.get('Firmware-level')
            chassis.firm_build = elems.get('Firmware-build')
            chassis.firm_name = elems.get('Firmware-name')

            result.append(chassis)

        return result
 def process(self, context):
     webseal_instance_osh = context.application.applicationOsh
     command_line = self._main_process.commandLine
     m = re.search('.*-config.+webseald-(\w+)', command_line)
     if m:
         logger.debug('Found instance name %s for Webseal Instance' % m.group(1))
         webseal_instance_osh.setStringAttribute('name', m.group(1))
         
     config_path = self._parseConfigPath(command_line)
     if not config_path:
         logger.warn('Failed to get more info')
     
     shell = context.client
     file_content = self._fetchConfigFileContent(shell, config_path)
     
     if not file_content:
         return
     
     master_host = self._parseMasterHostData(file_content)
     if not master_host:
         return
     
     ip = None
     
     if ip_addr.isValidIpAddressNotZero(master_host):
         ip = master_host
     else:
         try:
             resolver = dns_resolver.create(shell)
             ips = resolver.resolve_ips(master_host)
             ip = ips and ips[0]
         except:
             logger.debugException('Failed to resolve host name %s' % master_host)
     
     if ip:
         host_osh = modeling.createHostOSH(str(ip))
         if host_osh:
             policy_osh = self.buildPolicyServer(host_osh)
             link_osh = modeling.createLinkOSH('usage', webseal_instance_osh, policy_osh)
             vector = context.resultsVector
             vector.add(host_osh)
             vector.add(policy_osh)
             vector.add(link_osh)
 def _parseOutput(self, ipconfigBuffer, langBund):
     winsPrimServerIpPattern = self.langBund.getString(
         'windows_ipconfig_primary_wins_server').strip()
     winsSecServerIpPattern = self.langBund.getString(
         'windows_ipconfig_secondary_wins_server').strip()
     ips = []
     if ipconfigBuffer:
         for line in ipconfigBuffer.split('\n'):
             ipAddrBuffer = (re.match(winsPrimServerIpPattern, line)
                             or re.match(winsSecServerIpPattern, line))
             if ipAddrBuffer:
                 try:
                     raw_ip = ipAddrBuffer.group(1).strip()
                     if ip_addr.isValidIpAddressNotZero(raw_ip):
                         ips.append(ip_addr.IPAddress(raw_ip))
                 except:
                     logger.debug(
                         'Failed to transform to IP object value %s' %
                         ipAddrBuffer.group(1).strip())
     return ips
Exemple #19
0
 def __getDhcpServerIpList(self):
     ''' -> list(str)
     @raise Exception: if WMI query failed
     '''
     ips = []
     queryBuilder = self._wmiProvider.getBuilder(
         'Win32_NetworkAdapterConfiguration')
     queryBuilder.addWmiObjectProperties('dhcpServer')
     queryBuilder.addWhereClause('dhcpServer <> NULL')
     dhcpServerConfigurationList = self._wmiProvider.getAgent().getWmiData(
         queryBuilder)
     for dhcpServerConfiguration in dhcpServerConfigurationList:
         try:
             if ip_addr.isValidIpAddressNotZero(
                     dhcpServerConfiguration.dhcpServer):
                 ips.append(
                     ip_addr.IPAddress(dhcpServerConfiguration.dhcpServer))
         except:
             logger.debug('Failed to transform to IP object %s' %
                          dhcpServerConfiguration.dhcpServer)
         return ips
Exemple #20
0
    def _parseSubSystemData(self, output):
        result = []
        for chunk in re.split('[\r\n]{4}', output):
            if not (chunk and chunk.strip()):
                continue
            elems = parse_result_as_dict(chunk)
            st_node = ibm_fsm.StorageNode()
            host_name = elems.get('PrimaryHostName', '')
            if not netutils.isValidIp(host_name):
                if host_name.find('.') == -1:
                    st_node.hostname = host_name
                else:
                    st_node.hostname = host_name[:host_name.find('.')]

            ips_raw = elems.get('IPv4Address')
            if ips_raw:
                candidates = []
                if not isinstance(ips_raw, list):
                    candidates.append(ips_raw)
                else:
                    candidates = ips_raw

                for ip_str in candidates:
                    if ip_str and ip_addr.isValidIpAddressNotZero(ip_str):
                        st_node.ipList.append(ip_addr.IPAddress(ip_str))

            if not (st_node.hostname or st_node.ipList):
                continue

            st_node.description = '%s %s' % (elems.get('DisplayName'),
                                             elems.get('Description'))
            st_node.node_name = elems.get('NodeName')
            st_node.type = elems.get('MachineType')
            st_node.serial = elems.get('SerialNumber')
            st_node.vendor = elems.get('Manufacturer')
            st_node.model = elems.get('Model')
            st_node.os_version = elems.get('SoftwareVersion')
            result.append(st_node)
        return result
 def _parseChassisData(self, output):
     result = []
     for chunk in re.split('[\r\n]{4}', output):
         if not (chunk and chunk.strip()):
             continue
         elems = parse_result_as_dict(chunk)
         chassis = ibm_fsm.Chassis()
         host_name = elems.get('Hostname', '')
         if not netutils.isValidIp(host_name):
             if host_name.find('.') == -1:
                 chassis.hostname = host_name
             else:
                 chassis.hostname = host_name[:host_name.find('.')]        
         ips_raw = []       
         ips_raw.extend([x.strip() for x in elems.get('ipv4', '').strip(' []').split(',') if x and x.strip()])
         ips_raw.extend([x.strip() for x in elems.get('ipv6', '').strip(' []').split(',') if x and x.strip()])
         for ip_str in ips_raw:
             if ip_str and ip_addr.isValidIpAddressNotZero(ip_str):
                 chassis.ipList.append(ip_addr.IPAddress(ip_str))
 
         if not (chassis.hostname or chassis.ipList):
             continue
             
         if elems.get('NetInterface'): 
             chassis.iface.append( elems.get('NetInterface'))
         
         chassis.name = elems.get('Name')
         chassis.id = elems.get('Id')
         chassis.guid = elems.get('GUID')
         chassis.board_uuid = elems.get('System Board UUID')
         chassis.serial = elems.get('Serial Number')
         chassis.frim_level = elems.get('Firmware-level')
         chassis.firm_build = elems.get('Firmware-build')
         chassis.firm_name = elems.get('Firmware-name')
         
         result.append(chassis)
         
     return result
    def _parseSubSystemData(self, output):
        result = []
        for chunk in re.split('[\r\n]{4}', output):
            if not (chunk and chunk.strip()):
                continue
            elems = parse_result_as_dict(chunk)
            st_node = ibm_fsm.StorageNode()
            host_name = elems.get('PrimaryHostName', '')
            if not netutils.isValidIp(host_name):
                if host_name.find('.') == -1:
                    st_node.hostname = host_name
                else:
                    st_node.hostname = host_name[:host_name.find('.')]

            ips_raw = elems.get('IPv4Address')
            if ips_raw:
                candidates = []
                if not isinstance(ips_raw, list):
                    candidates.append(ips_raw)
                else:
                    candidates = ips_raw
                    
                for ip_str in candidates:
                    if ip_str and ip_addr.isValidIpAddressNotZero(ip_str):
                        st_node.ipList.append(ip_addr.IPAddress(ip_str))

            if not (st_node.hostname or st_node.ipList):
                continue
                  
            st_node.description = '%s %s' % (elems.get('DisplayName'), elems.get('Description')) 
            st_node.node_name = elems.get('NodeName')
            st_node.type = elems.get('MachineType')
            st_node.serial = elems.get('SerialNumber')
            st_node.vendor = elems.get('Manufacturer')
            st_node.model = elems.get('Model')
            st_node.os_version = elems.get('SoftwareVersion')
            result.append(st_node)
        return result
Exemple #23
0
    def discoverVirtualServers(self, f5Osh):
        queryBuilder = SnmpQueryBuilder('10.1.2.1')
        queryBuilder.addQueryElement(1, 'name')
        queryBuilder.addQueryElement(2, 'addressType')
        queryBuilder.addQueryElement(3, 'address', 'hexa')
        queryBuilder.addQueryElement(4, 'wildmaskType')
        queryBuilder.addQueryElement(5, 'wildmask')
        queryBuilder.addQueryElement(6, 'port')        
        queryBuilder.addQueryElement(9, 'enabled')        
        queryBuilder.addQueryElement(19, 'defaultPoolName')
        virtualServers = self.snmpAgent.getSnmpData(queryBuilder)

        nameToVirtualServerHelper = {}
        
        for virtualServer in virtualServers:
            if virtualServer.enabled == '0':
                continue
            
            #TODO: Deal with addressType. "0" means unknown, but we must specify port type when create ipServer osh
            ipAddress = self.convertToIp(virtualServer.address)
            if not ip_addr.isValidIpAddressNotZero(ipAddress):
                continue

            virtualServerHelper = VirtualServerHelper(virtualServer.name, ipAddress, f5Osh, virtualServer.port)
            virtualServerHelper.setDefaultPoolName(virtualServer.defaultPoolName)
            nameToVirtualServerHelper[virtualServer.name] = virtualServerHelper
            
        nameToPool = {}
        self.discoverPools(nameToVirtualServerHelper, f5Osh, nameToPool)
        self.discoverRules(nameToVirtualServerHelper, nameToPool)
        
        #report virtual servers only with links to cluster
        for virtualServerHelper in nameToVirtualServerHelper.values():
            if virtualServerHelper.hasAtLeastOneParentCluster():
                virtualServerHelper.addResultsToVector(self.OSHVResult)
            else:
                logger.debug("Virtual server %s was not reported since it is not linked to any cluster" % virtualServerHelper)
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    connection = Framework.getProbeDatabaseConnection('common')

    for mac_preffix, vendor in THIN_CLIENT_MAC_TO_VENDOR_PAIRS.items():
        st = getPreparedStatement(connection, mac_preffix)
        rs = st.executeQuery()
        while (rs.next()):
            mac = rs.getString('mac_address')
            ip = rs.getString('ip_address')
            if ip_addr.isValidIpAddressNotZero(
                    ip) and not DSM.isIpOutOfScope(ip) and DSM.isClientIp(ip):
                ip_osh = build_client_ip_osh(ip, mac)
                node_osh = build_node_osh(mac, vendor)
                if ip_osh and node_osh:
                    link_osh = modeling.createLinkOSH('containment', node_osh,
                                                      ip_osh)
                    interface_osh = modeling.createInterfaceOSH(mac, node_osh)
                    OSHVResult.add(ip_osh)
                    OSHVResult.add(node_osh)
                    OSHVResult.add(link_osh)
                    OSHVResult.add(interface_osh)
                else:
                    debug(
                        'Failed to create topology for ip %s , mac %s, vendor %s'
                        % (ip, mac, vendor))
            else:
                debug(
                    'Skipping IP address %s since it is invalid or not assigned to any probe or not in client ip range. '
                    % ip)
        rs.close()
        connection.close(st)

    connection.close()
    return OSHVResult
Exemple #25
0
 def __getWinsServerIpList(self):
     ''' -> list(str)
     @raise Exception: if WMI query failed
     '''
     ips = []
     queryBuilder = self._wmiProvider.getBuilder(
         'Win32_NetworkAdapterConfiguration')
     queryBuilder.addWmiObjectProperties('WinsPrimaryServer',
                                         'WinsSecondaryServer')
     queryBuilder.addWhereClause(
         'WinsPrimaryServer <> NULL or WinsSecondaryServer <> NULL')
     winsServerConfigurationList = self._wmiProvider.getAgent().getWmiData(
         queryBuilder)
     for winsServerConfiguration in winsServerConfigurationList:
         for ip in [
                 winsServerConfiguration.WinsPrimaryServer,
                 winsServerConfiguration.WinsSecondaryServer
         ]:
             try:
                 if ip_addr.isValidIpAddressNotZero(ip):
                     ips.append(ip_addr.IPAddress(ip))
             except:
                 logger.debug('Failed to transform to IP obj value %s' % ip)
     return ips
    def buildVm(self, server):
        vm = openstack.Vm()
        vm.referenced_project = server.getTenantId()
        vm.name = server.getName()
        vm.status = server.getStatus()
        vm.host_id = server.getHostId()
        vm.id = server.getId()
        image = server.getImage()
        if image:
            logger.debug("server.getImage():", image)
            vm.image = openstack.Image(image.getId())
        flavor = server.getFlavor()
        if flavor:
            logger.debug("server.getFlavor():", flavor)
            vm.flavor = openstack.Flavor(flavor.getId())
        getExtendedAttributes = server.getExtendedAttributes()
        vm.hypervisorHostName = getExtendedAttributes.get().getHypervisorHostName()

        addrs = server.getAddresses().values()
        for addr in addrs:
            ip = addr.getAddr()
            if ip and ip_addr.isValidIpAddressNotZero(ip):
                vm.ips.append(ip_addr.IPAddress(ip))
        return vm
def isValidIP(ip):
    return ip_addr.isValidIpAddressNotZero(ip)
Exemple #28
0
def isValidIP(ip):
    return ip_addr.isValidIpAddressNotZero(ip)
                    zoneRole.setZoneName(zoneName)

                if ifconfigRecord.ipmpGroupName:
                    ipmpGroup = self._getOrCreateIpmpGroup(ifconfigRecord.ipmpGroupName)
                    ipmpGroup.addInterface(interface)
                    if zloginZoneName:
                        ipmpGroup._setZoneName(zloginZoneName)

                try:
                    ip = networking.Ip(ifconfigRecord.ip, ifconfigRecord.mask)
                    network = networking.Network(ifconfigRecord.ip, ifconfigRecord.mask)
                    dhcpEnabled = 'DHCP' in ifconfigRecord.flags
                    if dhcpEnabled:
                        ip.setFlag(networking.Ip.FLAG_DHCP)

                    if ip_addr.isValidIpAddressNotZero(str(ip.ip)):
                        self.networking._addIp(ip, interface.name + (zoneName or u''))

                    self.networking._addNetwork(network)

                except (networking.InvalidIpException, networking.InvalidNetmaskException), ex:
                    logger.warn(str(ex))

    def _guessAggregationsByName(self):
        '''
        When dladm command is not available (zones) we can guess which interfaces are aggregations
        by name, since they have strict format "aggr<key>", but we won't be able to discover backing
        interfaces. We should omit aggregations with key > 999 since they denote VLANs.
        '''
        for interface in self.networking.getInterfaces():
            matcher = re.match(r"aggr(\d{1,3})$", interface.name, re.I)
    def _parseServerData(self, output):
        '''
        Parses command smcli "lssys -l -t Server" output
        @param output: string
        @return: list of ibm_fsm.Host instances
        '''
        result = []
        for chunk in re.split('[\r\n]{4}', output):
            if not (chunk and chunk.strip()):
                continue
            elems = parse_result_as_dict(chunk)
            if (elems.get('MachineType') and str(elems.get('MachineType')) in ('7863', '7955', '7917') ) \
                or (elems.get('MgmtHwType') and \
                    elems.get('MgmtHwType') in ['BaseboardManagementController']):
                logger.debug('Skipping management node')
                continue
            hostDo = ibm_fsm.Host()
            
            host_name = elems.get('HostName', '')
            #logger.debug('Got hostname %s' % host_name)
            if host_name:

                if isinstance(host_name, list):
                    host_name = host_name[0]

                if not netutils.isValidIp(host_name):
                    if host_name.find('.') == -1:
                        hostDo.hostname = host_name
                    else:
                        hostDo.hostname = host_name[:host_name.find('.')]
                        hostDo.domain = host_name[host_name.find('.')+1:]

            #logger.debug('Is virtual %s' % elems.get('Virtual'))
            hostDo.is_virtual = elems.get('Virtual') and elems.get('Virtual').strip() == 'true' or False
            hostDo.serial = elems.get('SerialNumber')
            hostDo.displayName = elems.get('DisplayName')
            #logger.debug('Serial %s' % elems.get('SerialNumber'))
            vendor = elems.get('Manufacturer')
            if vendor:
                  
                if vendor.find('(') != -1:
                    vendor = vendor[:vendor.find('(')]
                hostDo.vendor = vendor
            hostDo.model = elems.get('Model')
            hostDo.referenced_chassis = elems.get('ChassisName')
            hostDo.architecture = elems.get('Architecture')
            hostDo.server_type = elems.get('ServerType')
            hostDo.sys_uuid = elems.get('SystemBoardUUID')
            hostDo.name = elems.get('DisplayName')
            hostDo.vm_id = elems.get('VMID')
            #process IP addresses
            ips_raw = elems.get('IPv4Address')
            if ips_raw:
                candidates = []
                if not isinstance(ips_raw, list):
                    candidates.append(ips_raw)
                else:
                    candidates = ips_raw
                    
                for ip_str in candidates:
                    if ip_str and ip_addr.isValidIpAddressNotZero(ip_str):
                        hostDo.ipList.append(ip_addr.IPAddress(ip_str))
            
            #process MACs
            macs_raw = elems.get('MACAddress')
            if macs_raw:
                candidates = []
                if not isinstance(macs_raw, list):
                    candidates.append(macs_raw)
                else:
                    candidates = macs_raw
                
                for mac in candidates:
                    if netutils.isValidMac(mac):
                        hostDo.macs.append(netutils.parseMac(mac))
            result.append(hostDo)
        return result    
    def parseInterfaces(self, output):
        """
        This function performs parsing of interface related part from lsconfig -n command
        @param output: lsconfig -n command output 
        @type output: string
        @return: nwtworking information
        @rtype: UnixNetworking class instance
        """
        elems = re.split('(\n\s*eth)', output)
        #strip irrelevant part
        elems = elems and elems[1:]
        chunks = map(lambda x: ''.join(x), izip(elems[::2], elems[1::2]))
        fsm_networking = networking.UnixNetworking()
        for chunk in chunks:
            iface = networking.Interface()
            m = re.search('(eth\d+)', chunk)
            iface.name = m and m.group(1)
            
            m = re.search('mac_address_\w+:\s+([\w:]+)', chunk)
            mac = m and m.group(1)
            if netutils.isValidMac(mac):
                iface.mac = netutils.parseMac(mac)

            if not (iface.name and iface.mac):
                logger.debug('Neither name nor MAC is found for interface chunk "%s". Skipping' % chunk)
                continue
                
#            m = re.search('duplex_\w+:\s+(\w+)', chunk)
#            duplex = m and m.group(1)
            
            m = re.search('ipv4dhcp_\w+:\s+(\w+)', chunk)
            is_dhcpv4 = m and m.group(1)
            
            m = re.search('ipv6dhcp_\w+:\s+(\w+)', chunk)
            is_dhcpv6 = m and m.group(1)
            
            m = re.search('media_speed_\w+:\s+(\d+)\s+(\w+)', chunk)
            iface.speed = m and m.group(1)
            if m.group(2) and m.group(2).lower() != 'mbps':
                iface.speed = iface.speed * 1024
            
            fsm_networking.addInterface(iface)
            #IP related part
            m = re.search('ipv4addr_\w+:\s+([\d\.]+)', chunk)
            ipv4 = m and m.group(1)
            
            m = re.search('ipv4netmask_\w+:\s+([\d\.]+)', chunk)
            maskv4 = m and m.group(1)
            
            if ip_addr.isValidIpAddressNotZero(ipv4):
                fsm_networking.addIpAndNetwork(ipv4, maskv4, iface.name, is_dhcpv4)
            else:
                logger.debug('IP %s is invalid skipping.' % ipv4)
            m = re.search('ipv6addr_\w+:\s+(.+)', chunk)
            if m:
                for ip in m.group(1).split(','):
                    ipv6 = ip
                    mask = None
                    if ip.find('/') != -1:
                        elems = ip.split('/')
                        ipv6 = elems[0]
                        mask = elems[1]
                    if ip_addr.isValidIpAddressNotZero(ipv6):
                        fsm_networking.addIpAndNetwork(ipv6, mask, iface.name, is_dhcpv6)
                    else:
                        logger.debug('IP %s is invalid skipping.' % ipv6)
        return fsm_networking
Exemple #32
0
    def parseInterfaces(self, output):
        """
        This function performs parsing of interface related part from lsconfig -n command
        @param output: lsconfig -n command output 
        @type output: string
        @return: nwtworking information
        @rtype: UnixNetworking class instance
        """
        elems = re.split('(\n\s*eth)', output)
        #strip irrelevant part
        elems = elems and elems[1:]
        chunks = map(lambda x: ''.join(x), izip(elems[::2], elems[1::2]))
        fsm_networking = networking.UnixNetworking()
        for chunk in chunks:
            iface = networking.Interface()
            m = re.search('(eth\d+)', chunk)
            iface.name = m and m.group(1)

            m = re.search('mac_address_\w+:\s+([\w:]+)', chunk)
            mac = m and m.group(1)
            if netutils.isValidMac(mac):
                iface.mac = netutils.parseMac(mac)

            if not (iface.name and iface.mac):
                logger.debug(
                    'Neither name nor MAC is found for interface chunk "%s". Skipping'
                    % chunk)
                continue


#            m = re.search('duplex_\w+:\s+(\w+)', chunk)
#            duplex = m and m.group(1)

            m = re.search('ipv4dhcp_\w+:\s+(\w+)', chunk)
            is_dhcpv4 = m and m.group(1)

            m = re.search('ipv6dhcp_\w+:\s+(\w+)', chunk)
            is_dhcpv6 = m and m.group(1)

            m = re.search('media_speed_\w+:\s+(\d+)\s+(\w+)', chunk)
            iface.speed = m and m.group(1)
            if m.group(2) and m.group(2).lower() != 'mbps':
                iface.speed = iface.speed * 1024

            fsm_networking.addInterface(iface)
            #IP related part
            m = re.search('ipv4addr_\w+:\s+([\d\.]+)', chunk)
            ipv4 = m and m.group(1)

            m = re.search('ipv4netmask_\w+:\s+([\d\.]+)', chunk)
            maskv4 = m and m.group(1)

            if ip_addr.isValidIpAddressNotZero(ipv4):
                fsm_networking.addIpAndNetwork(ipv4, maskv4, iface.name,
                                               is_dhcpv4)
            else:
                logger.debug('IP %s is invalid skipping.' % ipv4)
            m = re.search('ipv6addr_\w+:\s+(.+)', chunk)
            if m:
                for ip in m.group(1).split(','):
                    ipv6 = ip
                    mask = None
                    if ip.find('/') != -1:
                        elems = ip.split('/')
                        ipv6 = elems[0]
                        mask = elems[1]
                    if ip_addr.isValidIpAddressNotZero(ipv6):
                        fsm_networking.addIpAndNetwork(ipv6, mask, iface.name,
                                                       is_dhcpv6)
                    else:
                        logger.debug('IP %s is invalid skipping.' % ipv6)
        return fsm_networking
Exemple #33
0
    def _parseServerData(self, output):
        '''
        Parses command smcli "lssys -l -t Server" output
        @param output: string
        @return: list of ibm_fsm.Host instances
        '''
        result = []
        for chunk in re.split('[\r\n]{4}', output):
            if not (chunk and chunk.strip()):
                continue
            elems = parse_result_as_dict(chunk)
            if (elems.get('MachineType') and str(elems.get('MachineType')) in ('7863', '7955', '7917') ) \
                or (elems.get('MgmtHwType') and \
                    elems.get('MgmtHwType') in ['BaseboardManagementController']):
                logger.debug('Skipping management node')
                continue
            hostDo = ibm_fsm.Host()

            host_name = elems.get('HostName', '')
            #logger.debug('Got hostname %s' % host_name)
            if host_name:

                if isinstance(host_name, list):
                    host_name = host_name[0]

                if not netutils.isValidIp(host_name):
                    if host_name.find('.') == -1:
                        hostDo.hostname = host_name
                    else:
                        hostDo.hostname = host_name[:host_name.find('.')]
                        hostDo.domain = host_name[host_name.find('.') + 1:]

            #logger.debug('Is virtual %s' % elems.get('Virtual'))
            hostDo.is_virtual = elems.get('Virtual') and elems.get(
                'Virtual').strip() == 'true' or False
            hostDo.serial = elems.get('SerialNumber')
            hostDo.displayName = elems.get('DisplayName')
            #logger.debug('Serial %s' % elems.get('SerialNumber'))
            vendor = elems.get('Manufacturer')
            if vendor:

                if vendor.find('(') != -1:
                    vendor = vendor[:vendor.find('(')]
                hostDo.vendor = vendor
            hostDo.model = elems.get('Model')
            hostDo.referenced_chassis = elems.get('ChassisName')
            hostDo.architecture = elems.get('Architecture')
            hostDo.server_type = elems.get('ServerType')
            hostDo.sys_uuid = elems.get('SystemBoardUUID')
            hostDo.name = elems.get('DisplayName')
            hostDo.vm_id = elems.get('VMID')
            #process IP addresses
            ips_raw = elems.get('IPv4Address')
            if ips_raw:
                candidates = []
                if not isinstance(ips_raw, list):
                    candidates.append(ips_raw)
                else:
                    candidates = ips_raw

                for ip_str in candidates:
                    if ip_str and ip_addr.isValidIpAddressNotZero(ip_str):
                        hostDo.ipList.append(ip_addr.IPAddress(ip_str))

            #process MACs
            macs_raw = elems.get('MACAddress')
            if macs_raw:
                candidates = []
                if not isinstance(macs_raw, list):
                    candidates.append(macs_raw)
                else:
                    candidates = macs_raw

                for mac in candidates:
                    if netutils.isValidMac(mac):
                        hostDo.macs.append(netutils.parseMac(mac))
            result.append(hostDo)
        return result