示例#1
0
 def __initializeSANScreenEndPoint(self):
     try:
         ## Get SANscreen credentials
         sanscreenProtocols = self.framework.getAvailableProtocols(self.sanscreenIpAddress, "sanscreen")
         if sanscreenProtocols == None or len(sanscreenProtocols) < 1:
             logger.reportError("No SANscreen credentials found for [%s] destination" % self.sanscreenIpAddress)
             return None
         else:
             for protocol in sanscreenProtocols:
                 soapPort = self.framework.getProtocolProperty(protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT) or '80'
                 soapProtocol = self.framework.getProtocolProperty(protocol, 'sanscreenprotocol_protocol')
                 username = self.framework.getProtocolProperty(protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_USERNAME)
                 password = self.framework.getProtocolProperty(protocol, CollectorsConstants.PROTOCOL_ATTRIBUTE_PASSWORD)
                 ## Should have everything to try connecting...
                 try:
                     ## Try connecting
                     ## Set URL and system properties
                     serviceURL = soapProtocol + '://' + self.sanscreenIpAddress + ':' + soapPort + '/sanscreenapi'
                     return SSApiWrapper().getEndpoint(serviceURL, username, password)
                 except:
                     excInfo = logger.prepareJythonStackTrace('Will try next credential entry (if available) due to exception: ')
                     logger.warn('[initializeSANScreenEndPoint] Exception: <%s>' % excInfo)
                     # Try next credential entry
                     continue
     except:
         excInfo = logger.prepareJythonStackTrace('')
         logger.warn('[initializeSANScreenEndPoint] Exception: <%s>' % excInfo)
         pass
def resolveIpFromDns(Framework, ipOrDnsOrAlias, localShell, dnsServers = None):
    normalizedIp = str(ipOrDnsOrAlias).strip()

    if not normalizedIp or normalizedIp == "localhost" or (ip_addr.isValidIpAddress(normalizedIp) and (ip_addr.IPAddress(normalizedIp).is_loopback or ip_addr.IPAddress(normalizedIp).is_multicast)):
        logger.debug('Skipped ip [', normalizedIp, '] for next hop, because it is empty or loopback or not a valid ip address')
        return None

    if dnsServers is not None:
        logger.debug('Trying to resolve ip using provided dnsServers names')
        dnsResolver = netutils.DNSResolver(localShell)
        for dnsServer in dnsServers:
            logger.debug('Trying to resolve ip using DNS Server [', dnsServer, ']')
            try:
                resolvedIp = dnsResolver.resolveHostIp(normalizedIp, dnsServer)
                if resolvedIp is not None:
                    logger.debug('Resolved ip [', resolvedIp, '] from [', normalizedIp, '] using DNS Server [', dnsServer, ']')
                    return resolvedIp
            except:
                Framework.reportWarning(logger.prepareJythonStackTrace(''))
                logger.debug('Failed to resolve [', normalizedIp, ']')

    try:
        logger.debug('Trying to resolve ip using local DNS server')
        resolvedIp = netutils.resolveIP(localShell, normalizedIp)
        if resolvedIp is not None:
            logger.debug('Resolved ip [', resolvedIp, '] from [', normalizedIp, '] using configured local DNS Server or hosts file')
            return resolvedIp
        else:
            errorMessage = 'Failed to resolve ip from [' + normalizedIp + '] using configured local DNS Server or hosts file'
            Framework.reportWarning(errorMessage)
            logger.warn(errorMessage)
    except:
        Framework.reportWarning(logger.prepareJythonStackTrace(''))
        logger.warn(errorMessage)
    return resolvedIp
def getProcListBySNMP(localClient):
	try:
		dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcListBySNMP]')
		procToPortDict = {}
		HOST_IP = localClient.getIpAddress()

		## Not using SNMP HR scripts since they are not split into a main discovery and
		## utils script. Using them will result in those discoveries being executed for
		## this destination and host resource data will be added to the CMDB

		## Not getting services using SNMP because only running services are
		## available, and if a service is running, we would already have the database
		## in the list of running processes. Service path, which would be useful, is
		## not available by SNMP

		## Not getting software either because only installed software names are
		## available. Version and path information are not available.

		## Get a list of processes
		try:
			resultSet = localClient.executeQuery('1.3.6.1.2.1.25.4.2.1.1,1.3.6.1.2.1.25.4.2.1.2,string,1.3.6.1.2.1.25.4.2.1.4,string,1.3.6.1.2.1.25.4.2.1.5,string,1.3.6.1.2.1.25.5.1.1.2,string,1.3.6.1.2.1.25.5.1.1.1,string,1.3.6.1.2.1.25.4.2.1.2,string')
			while resultSet.next():
				## Name
				processName = resultSet.getString(7).strip()
				if processName == None or processName == '' or len(processName) <1:
					## We don't care about nameless processes
					continue
				pid = resultSet.getString(2).strip()				## PID
				processPath = resultSet.getString(3).strip()		## Path
				processPath = string.replace(processPath, '"', '')
				processCmdline = resultSet.getString(4).strip()	## Command line
				processCmdline = string.replace(processCmdline, '"', '')
				## Add this to the dictionary
				dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcListBySNMP] Got PROCESS <%s:%s> with path <%s> and command line <%s>' % (pid, processName, processPath, processCmdline))
				## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
				procToPortDict[pid] = [processName, dbconnect_utils.UNKNOWN, HOST_IP, processPath, dbconnect_utils.UNKNOWN, 'Running', processCmdline]
		except:
			excInfo = logger.prepareJythonStackTrace('')
			logger.debug('[' + SCRIPT_NAME + ':getProcListBySNMP] Unable to get a list of proceses: <%s>' % excInfo)
			pass

		## Should have proc to port map
		if len(procToPortDict) > 0:
			dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcListBySNMP] Returning process to port dictionary with <%s> items' % len(procToPortDict))
			return procToPortDict
		else:
			dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcListBySNMP] Returning EMPTY process to port dictionary')
			return None
	except:
		excInfo = logger.prepareJythonStackTrace('')
		dbconnect_utils.debugPrint('[' + SCRIPT_NAME + ':getProcListBySNMP] Exception: <%s>' % excInfo)
		pass
def getAIXpIDfromAddress(localClient, procAddress, USE_SUDO):
    try:
        kdbOut = ''
        kdbCmd = ''
        pidLine = ''
        kdbOutLines = []
        try:
            kdbCmd = 'echo "sockinfo ' + procAddress + ' tcpcb" | kdb | grep ACTIVE'
            if USE_SUDO == 'true':
                kdbCmd = 'sudo ' + kdbCmd
            kdbOut = localClient.executeCmd(kdbCmd)
            ## Output: pvproc+00E000   56*inetd    ACTIVE 003808A 00360AC 0000000001244400   0 0001
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.warn('[' + SCRIPT_NAME + ':getAIXpIDfromAddress] Error: Couldn\'t execute <%s>: <%s>' % (kdbCmd, excInfo))
            return None
        ##
        if (kdbOut.find('do not allow') != -1):
            logger.debug('[' + SCRIPT_NAME + ':getAIXpIDfromAddress] Couldn\'t get info from kdb. Please set suid on /usr/sbin/kdb or use root credentials.')
            return None
        ## If output contains multiple lines, split them
        kdbOutLines = dbconnect_utils.splitCommandOutput(kdbOut.strip())
        if kdbOutLines == None:
            kdbOutLines = kdbOut.strip()
        dbconnect_utils.debugPrint(5, '[' + SCRIPT_NAME + ':getAIXpIDfromAddress] kdbOutLines before extracting pidLine is <%s> (length=<%s>)' % (kdbOutLines, len(kdbOutLines)))
        ### We're only interested in the line with string "ACTIVE" in it
        if len(kdbOutLines) > 0:
            for kdbOutLine in kdbOutLines:
                if re.search('ACTIVE', kdbOutLine):
                    pidLine = kdbOutLine.strip()
        else:
            dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getAIXpIDfromAddress] Unusable KDB output for address <%s>' % procAddress)
            return None
        ## Extract process ID hex from output of kbd
        #m = re.match('\S+\+\w+\s+\d+\*\S+\s+\S+\s+(\w+)\s+\w+\s+\w+\s+\w+\s+\w+\s+\w+\s+.*', pidLine)
        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getAIXpIDfromAddress] pidLine is <%s>' % pidLine)
        m = re.match('.*ACTIVE\s+(\w+)\s+.*', pidLine)
        if (m):
            #thePID = str(int(m.group(1), 16))
            thePID = str(int(m.group(1), 16))
            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getAIXpIDfromAddress] Found PID <%s> for address <%s>' % (thePID, procAddress))
            return thePID
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getAIXpIDfromAddress] Couldn\'t find PID for address [' + procAddress + ']')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getAIXpIDfromAddress] Exception: <%s>' % excInfo)
        pass
def DiscoveryMain(Framework):
	OSHVResult = ObjectStateHolderVector()
	
	urlString = Framework.getParameter(PARAM_URL)
	
	reportPoweredOffVms = 0
	reportPoweredOffVmsValue = Framework.getParameter(PARAM_REPORT_POWERED_OFF_VMS)
	if reportPoweredOffVmsValue and reportPoweredOffVmsValue.lower() =='true':
		reportPoweredOffVms = 1

	
	ipAddress = None
	try:
		urlObject = URL(urlString)
		hostname = urlObject.getHost()
		
		if not hostname:
			logger.debug("Hostname is not defined in URL '%s'" % urlString)
			raise MalformedURLException()
		
		ipAddress = vcloud_discover.getIpFromUrlObject(urlObject)
		if not ipAddress or not netutils.isValidIp(ipAddress) or netutils.isLocalIp(ipAddress):
			msg = "Failed to resolve the IP address of server from specified URL"
			errormessages.resolveAndReport(msg, vcloud_discover.VcloudProtocol.DISPLAY, Framework)
			return OSHVResult
		
	except MalformedURLException:
		msg = "Specified URL '%s' is malformed" % urlString
		errormessages.resolveAndReport(msg, vcloud_discover.VcloudProtocol.DISPLAY, Framework)
	except:
		msg = logger.prepareJythonStackTrace("")
		errormessages.resolveAndReport(msg, vcloud_discover.VcloudProtocol.DISPLAY, Framework)
	else:
		
		#configure how connections should be discovered/established
		connectionDiscoverer = vcloud_discover.ConnectionDiscoverer(Framework)
		urlGenerator = vcloud_discover.ConstantUrlGenerator(urlString)
		connectionDiscoverer.setUrlGenerator(urlGenerator)
		connectionDiscoverer.addIp(ipAddress)
		
		#configure how established/failed connection should be used
		connectionHandler = vcloud_discover.BaseDiscoveryConnectionHandler(Framework)
		topologyDiscoverer = vcloud_discover.createVcloudDiscoverer(Framework)
		topologyReporter = vcloud_report.createVcloudReporter(Framework, None, reportPoweredOffVms)
		connectionHandler.setDiscoverer(topologyDiscoverer)
		connectionHandler.setReporter(topologyReporter)
		
		connectionDiscoverer.setConnectionHandler(connectionHandler)
		
		connectionDiscoverer.initConnectionConfigurations()
		
		connectionDiscoverer.discover(firstSuccessful=0)
		
		if not connectionHandler.connected:
			for errorMsg in connectionHandler.connectionErrors:
				Framework.reportError(errorMsg)
			for warningMsg in connectionHandler.connectionWarnings:
				Framework.reportWarning(warningMsg)

	return OSHVResult
示例#6
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    protocol = Framework.getDestinationAttribute('Protocol')
    try:
        try:
            try:
                hostName = Framework.getDestinationAttribute('hostname')
                msMqManagerUcmdbId = Framework.getDestinationAttribute(
                    'msmq_id')
                msMqManagerOsh = modeling.createOshByCmdbIdString(
                    'msmqmanager', msMqManagerUcmdbId)
                client = Framework.createClient()
                shell = shellutils.ShellUtils(client)
                msMqDiscoverer = MsMqDiscoverer(shell, msMqManagerOsh,
                                                hostName)
                if msMqDiscoverer:
                    msMqDiscoverer.discover()
                    msMqDiscoverer.addResultsToVector(OSHVResult)
            finally:
                try:
                    shell and shell.closeClient()
                except:
                    logger.debugException('')
                    logger.error('Unable to close shell')
                if OSHVResult.size() == 0:
                    raise Exception, "Failed getting information about Microsoft Message Queue"

        except JavaException, ex:
            msg = ex.getMessage()
            errormessages.resolveAndReport(msg, protocol, Framework)
    except:
        msg = logger.prepareJythonStackTrace('')
        errormessages.resolveAndReport(msg, protocol, Framework)
    return OSHVResult
示例#7
0
def getNetDeviceAndPortOSHVs(localFramework):
    try:
        netDeviceCmdbIdList = localFramework.getTriggerCIDataAsList('netdevice_cmdbid')
        netDeviceNameList = localFramework.getTriggerCIDataAsList('netdevice_name')
        portCmdbIdList = localFramework.getTriggerCIDataAsList('port_cmdbid')
        portNameList = localFramework.getTriggerCIDataAsList('port_name')
        portIndexList = localFramework.getTriggerCIDataAsList('port_index')
        portVlanIdList = localFramework.getTriggerCIDataAsList('port_vlan')
        portContainerCmdbIdList = localFramework.getTriggerCIDataAsList('port_container_cmdbid')

        ## Build OSHVs using input TQL data
        netDeviceOSHV = buildNetDeviceOSHV(localFramework, netDeviceCmdbIdList, netDeviceNameList)
        portOSHV = buildPortOSHV(localFramework, portCmdbIdList, portNameList, portIndexList, portVlanIdList, portContainerCmdbIdList)

        if not (netDeviceOSHV or portOSHV):
            localFramework.reportError('Unable to build NetDevice or Port CIs from Input CI data! Please check adapter input configuration')
            return None
        else:
            ciscoworks_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getNetDeviceAndPortOSHVs] Got <%s> NetDevice and <%s> Port OSHs' % (netDeviceOSHV.size(), portOSHV.size()))

        ## Try OSH lookups
        #anOSH = ciscoworks_utils.getCiByAttributesFromOSHV(OSHVResult, 'physical_port', {'name':'Gi8/2', 'root_container':'bce192dd39319eefd4016166568a34ef', 'port_index':609})
        #if anOSH:
        #    print anOSH.toXmlString()
        return (netDeviceOSHV, portOSHV)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':getNetDeviceAndPortOSHVs] Exception: <%s>' % excInfo)
        pass
示例#8
0
def processARISXML(ARISfile, requestedObjectTypeList,
                   requestedRelationshipTypeList, requestedLocaleID):
    try:
        builder = SAXBuilder()
        doc = builder.build(ARISfile)
        rootElement = doc.getRootElement()
        objList = {
        }  # Index object list by "object definition ID" because link ends are defined based on object definition id

        # ###########################################
        # Process all the ARIS components first
        # These will map to UCMDB CIs
        # ###########################################
        groupElements = rootElement.getChildren('Group')
        if groupElements:
            for groupElement in groupElements:
                if groupElement:
                    objectElements = groupElement.getChildren('ObjDef')
                    if objectElements:
                        for objectElement in objectElements:
                            if objectElement:
                                ## Process objects
                                theObject = processObjectElement(
                                    objectElement, requestedObjectTypeList,
                                    requestedRelationshipTypeList,
                                    requestedLocaleID)
                                if theObject:
                                    objList[theObject.objectDefnID] = theObject
        return objList
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME +
                   ':processARISXML] Exception: <%s>' % excInfo)
        pass
示例#9
0
def getServiceNowRelTypeId(SNConnPropMap, relClass):
    try:
        table_name = 'cmdb_rel_type'
        stub = getStub(SNConnPropMap, table_name)
        if stub == None:
            debugPrint(2, '[getServiceNowRelTypeId] Unable to get SN API stub for table <%s>' % table_name)
            return

        getKeysAction = getAction(table_name, 'GetKeys')
        if getKeysAction == None:
            logger.error('[getServiceNowRelTypeId] Unable to get <GetKeys> SN action for table <%s>' % table_name)
            return None

        getKeysAction.setName(relClass)
        try:
            keys = stub.getKeys(getKeysAction).getSys_id()
        except:
            raise Exception('[getServiceNowRelTypeId] Error connecting to Service-Now while processing CIT <%s>' % table_name)


        if len(keys) > 1:
            logger.warn('[getServiceNowRelTypeId] Got <%s> sys_ids for relationship type <%s>...using the first one. More than one is not normal!' % (len(keys), relClass))
        debugPrint(4, '[getServiceNowRelTypeId] Got SN sys_id <%s> for SN relationship type <%s>' % (keys, relClass))
        return keys[0]
    except Exception, ex:
        raise Exception('[getServiceNowRelTypeId] ' + ex.getMessage())
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[getServiceNowRelTypeId] Exception: <%s>' % excInfo)
        pass
def findFile(localClient, fileName, rootDirectory, isWindows):
    try:
        findCommand = 'find -L %s -name %s -type f 2>/dev/null' % (rootDirectory, fileName)
        if isWindows == 'true':
            # findCommand = 'dir %s\%s /s /b' % (rootDirectory, fileName)
            findCommand = 'cd \"%s\" && dir %s /s /b' % (rootDirectory, fileName) # modified by Daniel La

        debugPrint(3, '[' + SCRIPT_NAME + ':findFile] Going to run find command: <%s>' % findCommand)
        findResults = str(localClient.executeCmd(findCommand, 120000))
        if isWindows == 'true':
            errorCode = str(localClient.executeCmd('echo %ERRORLEVEL%'))
            print 'ERRORCODE: ', errorCode, ' for command ', findCommand
            if errorCode and errorCode == '0':
                pass
            else:
                debugPrint(3, '[' + SCRIPT_NAME + ':findFile] Unable to find <%s> in <%s>' % (fileName, rootDirectory))
                return None
        # if findResults.find("File not found") > 0 or findResults.find("cannot find") > 0 or findResults.find("not set") > 0 or findResults.lower().find("permission") > 0 or len(findResults) < 1:
        if findResults.find("is invalid") > 0 or findResults.find("File not Found") > 0 or findResults.find("File not found") > 0 or findResults.find("cannot find") > 0 or findResults.find("not set") > 0 or findResults.lower().find("permission") > 0 or len(findResults) < 1: # modified by Daniel La
            debugPrint(3, '[' + SCRIPT_NAME + ':findFile] Unable to find <%s> in <%s>' % (fileName, rootDirectory))
            return None
        locations = splitCommandOutput(findResults.strip())
        if locations != None:
            for location in locations:
                debugPrint(3, '[' + SCRIPT_NAME + ':findFile] Found <%s>  at <%s> with length <%s>' % (fileName, location, len(location)))
        return locations
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME + ':findFile] Exception: <%s>' % excInfo)
        pass
def findDatabases(localClient, procToPortDict, dbInstanceDict, isWindows='true', wmiRegistryClient=None):
    try:
        ## DB2 cannot be discovered through an SNMP/WMI agent
        localClientType = localClient.getClientType()
        if localClientType not in ['telnet', 'ssh', 'ntadmin']:
            logger.error('[' + SCRIPT_NAME + ':findDatabase] DB2 discovery requires SSH/Telnet/NTCMD')
            return

        ## The best approach to find DB2 instances is to make a list of
        ## locations where DB2 may be installed and search through them.
        searchLocations = []
        ## Extract information from process to port dictionary first
        ## For DB2, it is not possible to get database details from this
        ## dictionary. the best approach is to get possible install
        ## locations of DB2 and find databases later
        processProcToPortDict(localClient, isWindows, procToPortDict, searchLocations)

        ## Use the list of possible install locations to identify valid
        ## install locations
        instanceLocations = getInstancePaths(localClient, isWindows, searchLocations)

        # used for debugging purposes only - Daniel La
        for instancePath in instanceLocations:
            logger.debug('***********instance path is: ' + instancePath)

        ## Get databases using instance locations
        if instanceLocations:
            getDatabases(localClient, isWindows, instanceLocations, dbInstanceDict)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        dbconnect_utils.debugPrint('[' + SCRIPT_NAME + ':findDatabases] Exception: <%s>' % excInfo)
        pass
示例#12
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    try:
        hostId = Framework.getDestinationAttribute('hostId')
        hostOsh = modeling.createOshByCmdbIdString('host_node', hostId)

        snmpClient = Framework.createClient()
        try:
            cssDiscoverer = createCssDiscoverer(snmpClient, Framework,
                                                OSHVResult, hostOsh)
            cssDiscoverer.discoverContentRules()
            cssDiscoverer.discoverServices()
        finally:
            snmpClient.close()
    except NoCssException:
        errobj = errorobject.createError(
            errorcodes.CSS_NOT_FOUND_ON_TARGET_HOST, None,
            'CSS was not found on target host')
        logger.reportErrorObject(errobj)
    except:
        errorMessage = logger.prepareJythonStackTrace('')
        logger.error(errorMessage)
        errormessages.resolveAndReport(errorMessage, 'SNMP', Framework)

    return OSHVResult
示例#13
0
def buildRppOSH(deviceName, deviceAssetNumber, deviceSerialNumber, rowName,
                gridLocation, spaceName, floorName, buildingName, rppOshDict,
                datacenterOshDict):
    try:
        rppDictKey = '%s ** %s ** %s ** %s ** %s ** %s ** %s' % (
            deviceName, deviceAssetNumber, deviceSerialNumber, gridLocation,
            spaceName, floorName, buildingName)
        if rppDictKey in rppOshDict.keys():
            debugPrint(
                3, '[buildRppOSH] Already processed RPP <%s>! Skipping...' %
                deviceName)
        else:
            debugPrint(2, '[buildRppOSH] RPP <%s> found' % deviceName)
            rppOSH = ObjectStateHolder('remote_power_panel')
            populateOSH(
                rppOSH, {
                    'name': deviceName,
                    'serial_number': deviceSerialNumber,
                    'floor': floorName,
                    'space_name': spaceName,
                    'grid_location': gridLocation,
                    'row_name': rowName
                })
            rppOSH.setContainer(datacenterOshDict[buildingName])
            rppOshDict[rppDictKey] = rppOSH
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':buildRppOSH] Exception: <%s>' % excInfo)
        pass
示例#14
0
def buildPduOSH(deviceName, deviceAssetNumber, deviceSerialNumber, rowName,
                gridLocation, spaceName, floorName, buildingName, pduOshDict,
                datacenterOshDict):
    try:
        pduDictKey = '%s ** %s ** %s ** %s ** %s ** %s ** %s' % (
            deviceName, deviceAssetNumber, deviceSerialNumber, gridLocation,
            spaceName, floorName, buildingName)
        if pduDictKey in pduOshDict.keys():
            debugPrint(
                3, '[buildPduOSH] Already processed PDU <%s>! Skipping...' %
                deviceName)
        else:
            debugPrint(2, '[buildPduOSH] PDU <%s> found' % deviceName)
            pduOSH = ObjectStateHolder('power_distribution_unit')
            populateOSH(
                pduOSH, {
                    'name': deviceName,
                    'serial_number': deviceSerialNumber,
                    'floor': floorName,
                    'space_name': spaceName,
                    'grid_location': gridLocation,
                    'row_name': rowName
                })
            pduOSH.setContainer(datacenterOshDict[buildingName])
            pduOshDict[pduDictKey] = pduOSH
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':buildPduOSH] Exception: <%s>' % excInfo)
        pass
示例#15
0
def buildRackOSH(rackName, rackAssetNumber, rackSerialNumber, rowName,
                 gridLocation, spaceName, floorName, buildingName, rackOshDict,
                 datacenterOshDict):
    try:
        rackDictKey = '%s ** %s ** %s ** %s ** %s ** %s ** %s ** %s' % (
            rackName, rackAssetNumber, rackSerialNumber, rowName, gridLocation,
            spaceName, floorName, buildingName)
        if rackDictKey in rackOshDict.keys():
            debugPrint(
                3, '[buildRackOSH] Already processed RACK <%s>! Skipping...' %
                rackName)
            return rackOshDict[rackDictKey]
        else:
            debugPrint(2, '[buildRackOSH] RACK <%s> found' % rackName)
            rackOSH = modeling.createCompleteHostOSH('rack', '')
            #rackOSH = modeling.createCompleteHostOSH('rack', str(hash(rackDictKey)))
            populateOSH(
                rackOSH, {
                    'name': rackName,
                    'serial_number': rackSerialNumber,
                    'floor': floorName,
                    'space_name': spaceName,
                    'grid_location': gridLocation,
                    'row_name': rowName
                })
            rackOSH.setContainer(datacenterOshDict[buildingName])
            rackOshDict[rackDictKey] = rackOSH
            return rackOSH
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':buildRackOSH] Exception: <%s>' % excInfo)
        pass
示例#16
0
def processARISXML(ARISfile, requestedObjectTypeList, requestedRelationshipTypeList, requestedLocaleID):
	try:
		builder = SAXBuilder()
		doc = builder.build(ARISfile)
		rootElement = doc.getRootElement()
		objList = {} # Index object list by "object definition ID" because link ends are defined based on object definition id

		# ###########################################
		# Process all the ARIS components first
		# These will map to UCMDB CIs
		# ###########################################
		groupElements = rootElement.getChildren('Group')
		if groupElements:
			for groupElement in groupElements:
				if groupElement:
					objectElements = groupElement.getChildren('ObjDef')
					if objectElements:
						for objectElement in objectElements:
							if objectElement:
								## Process objects
								theObject = processObjectElement(objectElement, requestedObjectTypeList, requestedRelationshipTypeList, requestedLocaleID)
								if theObject:
									objList[theObject.objectDefnID] = theObject
		return objList
	except:
		excInfo = logger.prepareJythonStackTrace('')
		debugPrint('[' + SCRIPT_NAME + ':processARISXML] Exception: <%s>' % excInfo)
		pass
示例#17
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    jobId = Framework.getDiscoveryJobId()
    host_id = Framework.getDestinationAttribute('id')
    host_name = Framework.getTriggerCIData('host_name')
    dnsServers = Framework.getTriggerCIDataAsList('dnsServers') or None

    try:
        host_name = host_name.split(" ")
        ips = pi_utils.getIPs(host_name[0], Framework)

        if not ips:
            raise ValueError()

        hostOSH = modeling.createOshByCmdbIdString('node', host_id)
        modeling.addHostAttributes(hostOSH, None, host_name[0])
        #OSHVResult.add(hostOSH)

        for ip in ips:
            ipRes = pi_utils.getIPOSHV(Framework, ip, None, dnsServers, False,
                                       True)
            if ipRes.size() > 0:
                OSHVResult.add(
                    modeling.createLinkOSH('containment', hostOSH,
                                           modeling.createIpOSH(ip)))
                OSHVResult.addAll(ipRes)
        if OSHVResult.size() <= 0:
            raise ValueError()
    except Exception, e:
        msg = logger.prepareJythonStackTrace(
            "Error getting IPs for %s: " % (host_name), e)
        errormessages.resolveAndReport(msg, jobId, Framework)
        logger.error(msg)
示例#18
0
def getMappingFileNames(mapingFilesListFileName):
    try:
        debugPrint(
            5, '[' + SCRIPT_NAME +
            ':getMappingFileNames] Got mapping file list file name: <%s>' %
            mapingFilesListFileName)
        mappingFileNameList = []
        mappingFilesListFile = open(mapingFilesListFileName, 'r')
        mappingFilesListFileContent = mappingFilesListFile.readlines()
        for mappingFilesListFileLine in mappingFilesListFileContent:
            mappingFileName = mappingFilesListFileLine.strip()
            debugPrint(
                4, '[' + SCRIPT_NAME +
                ':getMappingFileNames] Got potential mapping file name: <%s>' %
                mappingFileName)
            if mappingFileName[0:1] != '#':
                mappingFileNameList.append(mappingFileName)
            else:
                debugPrint(
                    5, '[' + SCRIPT_NAME +
                    ':getMappingFileNames] Ignoring comment: <%s>' %
                    mappingFileName)
        return mappingFileNameList
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME +
                    ':getMappingFileNames] Exception: <%s>' % excInfo)
        pass
示例#19
0
def getIpSubnetDict(localDbClient, ipAddressList, netDeviceID, netDeviceElementID, netDeviceName):
    try:
        ipSubnetDict = {}
        ipSubnetQuery = 'SELECT IPAddress, SubnetMask FROM dba.IPProtocolEndPoint WHERE NetworkElementId=%s' % netDeviceElementID
        ipSubnetResultSet = ciscoworks_utils.doQuery(localDbClient, ipSubnetQuery)

        ## Return if query returns no results
        if ipSubnetResultSet == None:
            logger.info('[' + SCRIPT_NAME + ':getIpSubnetDict] No IP Addresses found for Net Device <%s>' % netDeviceName)
            return None

        ## We have query results!
        while ipSubnetResultSet.next():
            ipAddress = ciscoworks_utils.getStringFromResultSet(ipSubnetResultSet, 1)
            subnetMask = ciscoworks_utils.getStringFromResultSet(ipSubnetResultSet, 2)
            if ipAddress:
                ## Discard duplicate IPs
                if ipAddress in ipAddressList:
                    ciscoworks_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getIpSubnetDict] Duplicate IP address <%s> on Network Device <%s> with ID <%s>!! Discarding...' % (ipAddress, netDeviceName, netDeviceElementID))
                    continue
                else:
                    ipAddressList.append(ipAddress)
                ## Create IP OSH
                if subnetMask:
                    ciscoworks_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getIpSubnetDict] Got IP <%s> with subnet mask <%s> for Net Device <%s> with ID <%s>' % (ipAddress, subnetMask, netDeviceName, netDeviceElementID))
                    ipSubnetDict[ipAddress] = netutils.parseNetMask(subnetMask)
                else:
                    ciscoworks_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getIpSubnetDict] Got IP <%s> without subnet mask for Net Device <%s> with ID <%s>' % (ipAddress, netDeviceName, netDeviceElementID))
                    ipSubnetDict[ipAddress] = ''

        return ipSubnetDict
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':getIpSubnetDict] Exception: <%s>' % excInfo)
        pass
def getFileContent(localClient, theFile, isWindows):
    try:
        ## Make sure the file exists
        lsCommand = 'ls -lA '
        if isWindows == 'true':
            lsCommand = 'dir '
            ## Change / to \ in file path
            theFile = string.replace(theFile, '/', '\\')
            debugPrint(3, '[' + SCRIPT_NAME + ':getFileContent] Windows config file path: <%s>' % theFile)
        debugPrint(3, '[' + SCRIPT_NAME + ':getFileContent] Going to run command: <%s>' % (lsCommand + theFile))
        lsResults = str(localClient.executeCmd(lsCommand + theFile))
        lsStr = lsResults.strip()
        debugPrint(3, '[' + SCRIPT_NAME + ':getFileContent] Result of file listing: <%s>' % lsStr)
        if (lsStr.find("No such file or directory") > 0) or (lsStr.find("File Not Found") > 0) or (lsStr.lower().find("error") > 0) or (lsStr.lower().find("illegal") > 0) or (lsStr.lower().find("permission") > 0):
            debugPrint(2, 'Unable to find file <%s>' % theFile)
            return None

        ## Get contents of config.xml
        catCommand = 'cat '
        if isWindows == 'true':
            catCommand = 'type '
        catResults = str(localClient.executeCmd(catCommand + theFile))
        if catResults == None or len(catResults) < 1:
            debugPrint(2, 'File <%s> is empty or invalid' % theFile)
            return None
        catStr = catResults.strip()
        return catStr
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME + ':getFileContent] Exception: <%s>' % excInfo)
        pass
示例#21
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    jobId = Framework.getDiscoveryJobId()
    host_id    = Framework.getDestinationAttribute('id')
    host_name = Framework.getTriggerCIData('host_name')
    dnsServers = Framework.getTriggerCIDataAsList('dnsServers') or None
        
    try:
        host_name = host_name.split(" ")
        ips = pi_utils.getIPs(host_name[0], Framework)
        
        if not ips:
            raise ValueError()
        
        hostOSH = modeling.createOshByCmdbIdString('node', host_id)
        modeling.addHostAttributes(hostOSH, None, host_name[0])
        #OSHVResult.add(hostOSH)       
        
        for ip in ips:
            ipRes = pi_utils.getIPOSHV(Framework, ip, None, dnsServers, False, True)
            if ipRes.size() > 0:               
                OSHVResult.add(modeling.createLinkOSH('containment',hostOSH,modeling.createIpOSH(ip)))
                OSHVResult.addAll(ipRes)
        if OSHVResult.size() <=0:
            raise ValueError()       
    except Exception, e:
        msg = logger.prepareJythonStackTrace("Error getting IPs for %s: " % (host_name), e)
        errormessages.resolveAndReport(msg, jobId, Framework)
        logger.error(msg)
示例#22
0
def DiscoveryMain(Framework):
    shell = None
    try:
        try:
            protocolName = __getProtocolName(Framework)
            discoverSharePointUrls = Boolean.parseBoolean(Framework.getParameter('discoverSharePointUrls'))
            reportIntermediateWebService = Framework.getParameter('reportIntermediateWebService')
            if reportIntermediateWebService:
                reportIntermediateWebService = Boolean.parseBoolean(reportIntermediateWebService)
            else:
                #set default value
                reportIntermediateWebService = 1
            relativeCommandTimeoutMultiplier = Framework.getParameter('relativeCommandTimeoutMultiplier')
            relativeCommandTimeoutMultiplier = int(relativeCommandTimeoutMultiplier)
            client = Framework.createClient()
            shell = ShellFactory().createShell(client)
            logger.debug('getting SharePoint discoverer for protocol %s' % protocolName)
            discoverer = sharepoint_win_shell.getDiscoverer(shell, protocolName, relativeCommandTimeoutMultiplier)
            logger.debug('got discoverer')
            resources = _discoverSharePoint(discoverer)
            resources.build()
            return resources.report(discoverSharePointUrls, reportIntermediateWebService)
        except SharePointException:
            logger.reportError()
            logger.debugException('')
        except JavaException, ex:
            strException = ex.getMessage()
            errormessages.resolveAndReport(strException, protocolName, Framework)
        except:
            strException = logger.prepareJythonStackTrace('')
            errormessages.resolveAndReport(strException, protocolName, Framework)
示例#23
0
def discoverStorageArrays(client):
    ''' Discover storage arrays and related topology

    @types: Client -> generator
    @return: generator of tuples witch such elements
        storage array osh
        list[tuple[Port, osh]]
        list[tuple[Hba, osh]]
        list[tuple[LogicalVolume, osh]]
    '''
    try:
        arrays = _query_storage_arrays(client)
        for array in arrays:
            storageArrayOSH = _build_storage_array(array)

            ports = _query_ports(partial(_query_storage_array_ports, client, array.id))
            portOshs = (_report_port(storageArrayOSH, port) for port in ports)
            port_2_osh = zip(ports, portOshs)

            hbas = _query_storage_array_hbas(client, array.id)
            hbas = _drop("HBAs without ECC ID", Hba.ad_id.fget, hbas)
            hbasOshs = (_report_hba(storageArrayOSH, h) for h in hbas)
            hba_2_osh = zip(hbas, hbasOshs)

            logical_volumes = _query_storage_array_logical_volumes(client, array.id)
            volumeOshs = (_report_logical_volume(storageArrayOSH, v) for v in logical_volumes)
            volume_2_osh = zip(logical_volumes, volumeOshs)
            yield storageArrayOSH, port_2_osh, hba_2_osh, volume_2_osh
    except (JException, Exception):
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':discoverStorageArrays] Exception: <%s>' % excInfo)
示例#24
0
def processVlanPortMap(portVlanIdMap):
    try:
        returnOSHV = ObjectStateHolderVector()
        if portVlanIdMap:
            for portVlanIdMapKey in portVlanIdMap.keys():
                vlanNameAndId = portVlanIdMapKey.split(':;:')
                vlanName = vlanNameAndId[0]
                vlanID = vlanNameAndId[1]
                ## Build VLAN OSH
                if vlanName and vlanName != 'N/A' and vlanID and vlanID != '-1' and type(eval(vlanID)) == type(1):
                    ## Get a list of port IDs from the port OSH list in this map
                    portOshList = portVlanIdMap[portVlanIdMapKey]
                    portIdList = []
                    for portOSH in portOshList:
                        portIdList.append(str(portOSH.getAttributeValue('port_index')))
                    portIdList.sort()

                    ciscoworks_utils.debugPrint(2, '[' + SCRIPT_NAME + ':processVlanPortMap] Got VLAN <%s> with <%s> ports, total VLANs <%s>' % (portVlanIdMapKey, len(portIdList), len(portVlanIdMap)))
                    vlanUniqueID = str(hash(':'.join(portIdList)))
                    if not vlanUniqueID:
                        vlanUniqueID = 1
                    #vlanOSH = modeling.createVlanOsh(vlanID, None, portIdList)
                    vlanOSH = ObjectStateHolder('vlan')
                    ciscoworks_utils.populateOSH(vlanOSH, {'name':vlanName, 'vlan_aliasname':vlanName, 'vlan_id':int(vlanID), 'vlan_unique_id':vlanUniqueID})
                    returnOSHV.add(vlanOSH)

                    ## Add a member link between this VLAN and all ports related to it
                    for portOSH in portOshList:
                        returnOSHV.add(modeling.createLinkOSH('membership', vlanOSH, portOSH))
        return returnOSHV
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':processVlanPortMap] Exception: <%s>' % excInfo)
        pass
示例#25
0
def getEnum(localDbClient, tableName):
    try:
        if not tableName:
            logger.warn('[' + SCRIPT_NAME + ':getEnum] Invalid tableName specified!')
            return ''
        debugPrint(5, '[' + SCRIPT_NAME + ':getEnum] Got table name <%s>' % tableName)
        returnDict = {}

        enumQuery = 'SELECT * FROM ' + tableName
        enumResultSet = doQuery(localDbClient, enumQuery)

        ## Return if query returns no results
        if not enumResultSet:
            logger.warn('[' + SCRIPT_NAME + ':getEnum] No enumerations in table <%s>' % tableName)
            return None

        ## We have query results!
        while enumResultSet.next():
            returnDict[enumResultSet.getString(2)] = enumResultSet.getString(1)

        debugPrint(5, '[' + SCRIPT_NAME + ':getEnum] Got <%s> items in enumeration from table name <%s>' % (len(returnDict), tableName))
        return returnDict
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':getEnum] Exception: <%s>' % excInfo)
        pass
示例#26
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    protocol = Framework.getDestinationAttribute('Protocol')
    try:
        try:
            try:
                hostName = Framework.getDestinationAttribute('hostname')
                msMqManagerUcmdbId = Framework.getDestinationAttribute('msmq_id')
                msMqManagerOsh = modeling.createOshByCmdbIdString('msmqmanager', msMqManagerUcmdbId)
                client = Framework.createClient()
                shell = shellutils.ShellUtils(client)
                msMqDiscoverer = MsMqDiscoverer(shell, msMqManagerOsh, hostName)
                if msMqDiscoverer:
                    msMqDiscoverer.discover()
                    msMqDiscoverer.addResultsToVector(OSHVResult)
            finally:
                try:
                    shell and shell.closeClient()
                except:
                    logger.debugException('')
                    logger.error('Unable to close shell')
                if OSHVResult.size() == 0:
                    raise Exception, "Failed getting information about Microsoft Message Queue"

        except JavaException, ex:
            msg =ex.getMessage()
            errormessages.resolveAndReport(msg, protocol, Framework)
    except:
        msg = logger.prepareJythonStackTrace('')
        errormessages.resolveAndReport(msg, protocol, Framework)
    return OSHVResult
示例#27
0
def getFileContent(shell, theFile):
    try:
        ## Make sure the file exists
        lsCommandPattern = 'ls -lA %s'
        if shell.isWinOs():
            lsCommandPattern = 'dir "%s"'
            ## Change / to \ in file path
            theFile = string.replace(theFile, '/', '\\')
            logger.debug('[getFileContent] Windows config file path: %s' % theFile)
        logger.debug('[getFileContent] Going to run command: %s' % (lsCommandPattern % theFile))
        lsResults = str(shell.execCmd(lsCommandPattern % theFile))
        lsStr = lsResults.strip()
        logger.debug('[getFileContent] Result of file listing: %s' % lsStr)
        if (lsStr.find("No such file or directory") > 0) or (lsStr.find("File Not Found") > 0) or (lsStr.lower().find("error") > 0) or (
                    lsStr.lower().find("illegal") > 0) or (lsStr.lower().find("permission") > 0) or (lsStr.lower().find("cannot be found") > 0):
            logger.debug('Unable to find file: %s' % theFile)
            return None

        ## Get contents of config.xml
        catCommandPattern = 'cat %s'
        if shell.isWinOs():
            catCommandPattern = 'type "%s"'
        catResults = str(shell.execCmd(catCommandPattern % theFile))
        if catResults == None or len(catResults) < 1:
            logger.debug('File [%s] is empty or invalid' % theFile)
            return None
        catStr = catResults.strip()
        return catStr
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[getFileContent] Exception: %s' % excInfo)
        pass
示例#28
0
def buildIntermediateCiXML(theCiElement, objectFromARIS):
    try:
        theCiElement.setAttribute('type', objectFromARIS.type)
        objectAttributeMap = objectFromARIS.attMap
        ## Add CI attributes
        if objectAttributeMap:
            for objectAttributeName in objectAttributeMap.keys():
                if objectAttributeName and objectAttributeMap[
                        objectAttributeName]:
                    fieldElement = Element('field')
                    fieldElement.setAttribute('name', objectAttributeName)
                    fieldElement.setText(
                        objectAttributeMap[objectAttributeName])
                    theCiElement.addContent(fieldElement)
                else:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':buildIntermediateCiXML] Skipping attribute <%s> with invalid value'
                        % objectAttributeName)
        return 1
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME +
                   ':buildIntermediateCiXML] Exception: <%s>' % excInfo)
        return -1
示例#29
0
def verifyDB(localDbClient, dbName):
    try:
        returnVal = -1
        dbStateQuery = 'SELECT db_name()'
        debugPrint(4, '[' + SCRIPT_NAME + ':verifyDB] Running query <%s>' % dbStateQuery)
        dbStateResultSet = doQuery(localDbClient, dbStateQuery)

        ## Return if query returns no results
        if dbStateResultSet == None:
            logger.warn('[' + SCRIPT_NAME + ':verifyDB] Unable to get database name!')
            return returnVal

        ## We have query results!
        while dbStateResultSet.next():
            databaseName = dbStateResultSet.getString(1).strip()
            if databaseName.lower().strip() == dbName.lower().strip():
                debugPrint(5, '[' + SCRIPT_NAME + ':verifyDB] Database name <%s> OK' % dbName)
                returnVal = 1
            else:
                logger.error('[' + SCRIPT_NAME + ':verifyDB] Database name mismatch!! Should be <%s>, got <%s>...' % (dbName, databaseName))
                return returnVal

        return returnVal
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':verifyDB] Exception: <%s>' % excInfo)
        pass
示例#30
0
def buildNetDeviceOSHV(localFramework, netDeviceCmdbIdList, netDeviceNameList):
    try:
        returnOSHV = ObjectStateHolderVector()
        ## Check validity of provided lists
        if not netDeviceCmdbIdList:
            localFramework.reportError('Please check adapter parameter <netdevice_cmdbid>')
            return None
        if not netDeviceNameList:
            localFramework.reportError('Please check adapter parameter <netdevice_name>')
            return None
        if len(netDeviceCmdbIdList) != len(netDeviceNameList):
            localFramework.reportError('The lists <netdevice_cmdbid> and <netdevice_name> have different sizes: <%s> and <%s>! Please check adapter input configuration' \
                        % (len(netDeviceCmdbIdList), len(netDeviceNameList)))
            return None

        ## Build OSH and dict
        for netDeviceIndex in range(len(netDeviceCmdbIdList)):
            netDeviceCmdbId = netDeviceCmdbIdList[netDeviceIndex]
            netDeviceName = netDeviceNameList[netDeviceIndex]
            ## Check if attributes are good
            if not netDeviceCmdbId or not netDeviceName:
                logger.debug('Skipping invalid NetDevice name or CMDB ID in adapter input parameter...')
                continue
            ## Build OSH and add to OSHV
            netDeviceOSH = modeling.createOshByCmdbIdString('netdevice', netDeviceCmdbId)
            #netDeviceOSH.setAttribute('name', netDeviceName)
            netDeviceOSH.setAttribute('data_externalid', netDeviceName)
            ciscoworks_utils.debugPrint(4, '[' + SCRIPT_NAME + ':buildNetDeviceOSHV] Built OSH for NetDevice <%s> with CMDB ID <%s>' % (netDeviceName, netDeviceCmdbId))
            returnOSHV.add(netDeviceOSH)
        return returnOSHV
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':buildNetDeviceOSHV] Exception: <%s>' % excInfo)
        pass
示例#31
0
def connectToDb(localFramework, ipAddress, dbPort):
    try:
        theDbClient = None
        ## Get protocols
        protocols = localFramework.getAvailableProtocols(ipAddress, ClientsConsts.SQL_PROTOCOL_NAME)
        for protocolID in protocols:
            ## If this protocol entry is not for a Sybase DB, ignore it
            if localFramework.getProtocolProperty(protocolID, CollectorsConstants.SQL_PROTOCOL_ATTRIBUTE_DBTYPE) != 'Sybase':
                debugPrint(5, '[' + SCRIPT_NAME + ':DiscoveryMain] Ignoring non Sybase protocol entry...')
                continue
            ## Don't bother reconnecting if a connection has already been established
            if not theDbClient:
                ## Set DB properties
                dbConnectionProperties = Properties()
                dbConnectionProperties.setProperty(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, dbPort)
                # Establish JDBC connection
                debugPrint(5, '[' + SCRIPT_NAME + ':connectToDb] Attempting connection to CiscoWorks database at port <%s>...' % dbPort)
                try:
                    theDbClient = localFramework.createClient(protocolID, dbConnectionProperties)
                except:
                    theDbClient and theDBClient.close()
        return theDbClient
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':connectToDb] Exception: <%s>' % excInfo)
        pass
示例#32
0
def DiscoveryMain(Framework):
    properties = Properties()

    properties.setProperty('timeoutDiscover',
                           Framework.getParameter('timeoutDiscover'))
    properties.setProperty('retryDiscover',
                           Framework.getParameter('retryDiscover'))
    properties.setProperty('pingProtocol',
                           Framework.getParameter('pingProtocol'))
    properties.setProperty('threadPoolSize',
                           Framework.getParameter('threadPoolSize'))

    virtualMode = Framework.getParameter(
        'virtualModeDiscover').lower() == "true"
    byRangeFlag = Framework.getParameter("byScopeDiscover").lower() == "true"

    netAddress = Framework.getDestinationAttribute("netAddress")
    netMask = Framework.getDestinationAttribute("netMask")
    probeName = Framework.getDestinationAttribute("probeName")

    ignoreClientType = getGlobalSetting().getPropertyStringValue(
        'pingClientTypeIp', "False").lower() == "false"

    try:
        client = Framework.createClient(ClientsConsts.ICMP_PROTOCOL_NAME,
                                        properties)
        try:
            ipRange = getRangeByNetwork(netAddress, netMask)
            if byRangeFlag:
                rangesList = icmp_utils.getProbeRanges([ipRange], probeName,
                                                       Framework)
            else:
                rangesList = [ipRange]
            logger.info('Start working on range: ', len(rangesList))
            totalReportedIps = 0
            for aRange in rangesList:
                totalReportedIps += icmp_utils.pingIPsInRange(
                    Framework,
                    client,
                    aRange,
                    virtualMode,
                    netAddress,
                    netMask,
                    ignoreClientType=ignoreClientType)
                Framework.saveState(aRange.toRangeString())

            logger.debug('Total reported IPs %s ' % totalReportedIps)
            logger.info('Finished working on all ranges..')
            Framework.clearState()
            if not totalReportedIps:
                logger.reportWarning(
                    "No live DataCenter IPs found in probe ranges")
        finally:
            client.close()
    except:
        msg = logger.prepareJythonStackTrace('')
        errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME,
                                       Framework)
    return ObjectStateHolderVector()
示例#33
0
def DiscoveryMain(Framework):
    properties = Properties()
    vector = ObjectStateHolderVector()
    properties.setProperty('timeoutDiscover',
                           Framework.getParameter('timeoutDiscover'))
    properties.setProperty('retryDiscover',
                           Framework.getParameter('retryDiscover'))
    properties.setProperty('pingProtocol',
                           Framework.getParameter('pingProtocol'))
    properties.setProperty('threadPoolSize',
                           Framework.getParameter('threadPoolSize'))
    ip = Framework.getDestinationAttribute('ip_address')
    domainName = Framework.getDestinationAttribute('domain_name')
    id = Framework.getTriggerCIData('id')
    ports = getUDAAvailablePorts(Framework)

    try:
        client = Framework.createClient(ClientsConsts.ICMP_PROTOCOL_NAME,
                                        properties)
        try:
            range_uda_status = {}
            range_result = pingIPsInRange(Framework, client, ip, ports)
            range_uda_status.update(range_result)

            for x in range_uda_status.values():
                logger.debug(x)
                #build the udaStatus
                context = UdaState.Builder(x.ip).computerName(
                    x.computerName
                ).alive(x.alive).portAlive(x.portAlive).isDDMI(
                    x.isDDMI).isNative(x.isNative).isWin(x.isWin).osType(
                        x.osType).agentVersion(
                            str(x.agentVersion) +
                            ('-fips' if x.isFIPSEnabled else '')).UDUniqueId(
                                x.UDUniqueId).build()
                #save
                UdaStatusService.getInstance().saveUdaStatus(context)
                if Framework.getParameter('isCreateUDA') == 'true':
                    if x.UDUniqueId:
                        hostOsh = modeling.createHostOSH(x.ip)
                        hostOsh.setStringAttribute(
                            InventoryUtils.ATTR_UD_UNIQUE_ID, x.UDUniqueId)
                        uda = ObjectStateHolder('uda')
                        uda.setStringAttribute('application_ip', x.ip)
                        uda.setStringAttribute('application_ip_domain',
                                               domainName)
                        uda.setStringAttribute('discovered_product_name',
                                               'uda')
                        uda.setStringAttribute('version', str(x.agentVersion))
                        uda.setContainer(hostOsh)
                        vector.add(hostOsh)
                        vector.add(uda)
        finally:
            client.close()
    except:
        msg = logger.prepareJythonStackTrace('')
        errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME,
                                       Framework)
    return vector
示例#34
0
def DiscoveryMain(Framework):
	logger.info('Start Phase 1 ... Pull from ARIS')

	# Set global framework
	global theFramework
	theFramework = Framework

	## Make sure we have an input data file from ARIS
	ARISfileName = Framework.getParameter('ARIS_XML_file') or None
	ARISfile = File(ARISfileName)
	if not (ARISfile and ARISfile.exists() and ARISfile.canRead()):
		excInfo = ('ARIS XML input file is not specified or is invalid!')
		Framework.reportError(excInfo)
		logger.error(excInfo)
		return None

	## Check that the language parameter is set - default to US English
	requestedLocaleID = Framework.getParameter('ARISLocaleId') or '&LocaleId.USen;'
	if not requestedLocaleID:
		logger.warn('ARIS LocaleID parameter is not set...defaulting to US English')
		requestedLocaleID = '&LocaleId.USen;'

	# File and directory names
	userExtDir = CollectorsParameters.BASE_PROBE_MGR_DIR + CollectorsParameters.getDiscoveryResourceFolder() + '\\TQLExport\\ARIS\\'
	intermediatesDir = userExtDir + 'inter\\'
	mapingFilesListFileName = userExtDir + 'tqls.txt'
	mappingFileNameList = checkDiscoveryResources(mapingFilesListFileName, userExtDir, Framework, intermediatesDir)
	if not mappingFileNameList:
		return None

	## Get attribute names from mapping file(s)
	## This is a list of extended attributes to be retrieved from ARIS
	for mappingFileName in mappingFileNameList:
		(requestedSourceObjectTypeList, requestedSourceRelationshipTypeList) = getMapping(userExtDir + 'data\\' + mappingFileName + '.xml')
		if requestedSourceObjectTypeList and requestedSourceRelationshipTypeList:
			arisObjectMap = processARISXML(ARISfile, requestedSourceObjectTypeList, requestedSourceRelationshipTypeList, requestedLocaleID)
			intermediateXmlDoc = None
			if arisObjectMap:
				intermediateXmlDoc = buildIntermediateXML(arisObjectMap)
				intermediateXmlLocation = intermediatesDir + mappingFileName + '.xml'
			else:
				Framework.reportWarning('No CIs found in the ARIS XML file')

			if intermediateXmlDoc:
				try:
					xmlOutputter = XMLOutputter()
					xmlOutputter.output(intermediateXmlDoc, FileOutputStream(intermediateXmlLocation))
				except:
					excInfo = logger.prepareJythonStackTrace('')
					Framework.reportError('Error writing intermediate file: <%s>' % intermediateXmlLocation)
					logger.warn('[' + SCRIPT_NAME + ':DiscoveryMain] Exception: <%s>' % excInfo)
					pass
			else:
				Framework.reportWarning('Error creating intermediate XML')
		else:
			logger.warn('[' + SCRIPT_NAME + ':DiscoveryMain] Unable to process mapping file: <%s>' % mappingFileName)
			Framework.reportError(' Unable to process mapping file: <%s>' % mappingFileName)

	logger.info('End Phase 1.... Pull from ARIS')
示例#35
0
def addOshFromDictToOshv(oshDict, oshVector):
	try:
		for OSH in oshDict.keys():
			oshVector.add(oshDict[OSH])
	except:
		excInfo = logger.prepareJythonStackTrace('')
		logger.debug('[' + SCRIPT_NAME + ':addOshFromDictToOshv] Exception: <%s>' % excInfo)
		pass
def getDbDirectory(localClient, listDbDirectoryCommand):
    try:
        DbDirectory = localClient.executeCmd(listDbDirectoryCommand)
        return DbDirectory
    except:
        excInfo = logger.prepareJythonStackTrace('')
        dbconnect_utils.debugPrint('[' + SCRIPT_NAME + ':getDbDirectory] Exception: <%s>' % excInfo)
        pass
示例#37
0
def processException(errorsList, warnList, msg = None): 
    excInfo = logger.prepareJythonStackTrace('')
    logger.error('AS400 Discovery Exception: <%s>' % excInfo)
    if msg:
        excInfo = msg
    else:
        excInfo = str(sys.exc_info()[1])
    errormessages.resolveAndAddToObjectsCollections(excInfo, protocolName, warnList, errorsList)
示例#38
0
def getPowerRoutes(localFramework, localsqlClient, datacenterOshDict, rackOshDict, pduOshDict, rppOshDict, hostOshDict):
	try:
		resultVector = ObjectStateHolderVector()

		###########################
		## JDBC SQL stuff
		###########################
		## Build query
		powerRouteQuery = '''SELECT Downstream_Device_Name, Downstream_Device_Asset_Number, Downstream_Device_Serial_Number,
								Upstream_Device_Name, Upstream_Device_Asset_Number, Upstream_Device_Serial_Number, Upstream_Grid_Location, Upstream_Space_Name, Upstream_Floor, Upstream_Building_Name
							FROM vista.dbo.VIP_DAL_PWR_Device_Power_Sources'''
		debugPrint(3, '[getPowerRoutes] Power route query is <%s>' % powerRouteQuery)
		powerRouteQueryResultSet = localsqlClient.executeQuery(powerRouteQuery)

		## Do we have query results?
		if powerRouteQueryResultSet is None:
				debugPrint(1, '[getPowerRoutes] Empty result set for Rower Route query')
				localFramework.reportWarning('Unable to get a list of Power Routes')
				return None

		# Add all results to the OSHV
		addOshFromDictToOshv(datacenterOshDict, resultVector)

		## We have query results!
		while powerRouteQueryResultSet.next():
			deviceName = (powerRouteQueryResultSet.getString(1) or ' ').strip()
			deviceAssetNumber = (powerRouteQueryResultSet.getString(2) or ' ').strip()
			deviceSerialNumber = (powerRouteQueryResultSet.getString(3) or ' ').strip()
			pduName = (powerRouteQueryResultSet.getString(4) or ' ').strip()
			pduAssetNumber = (powerRouteQueryResultSet.getString(5) or ' ').strip()
			pduSerialNumber = (powerRouteQueryResultSet.getString(6) or ' ').strip()
			pduGridLocation = (powerRouteQueryResultSet.getString(7) or ' ').strip()
			pduSpaceName = (powerRouteQueryResultSet.getString(8) or ' ').strip()
			pduFloorName = (powerRouteQueryResultSet.getString(9) or ' ').strip()
			pduBuildingName = (powerRouteQueryResultSet.getString(10) or ' ').strip()

			## Build keys
			deviceKey = '%s ** %s ** %s' % (deviceName, deviceAssetNumber, deviceSerialNumber)
			pduKey = '%s ** %s ** %s ** %s ** %s ** %s ** %s' % (pduName, pduAssetNumber, pduSerialNumber, pduGridLocation, pduSpaceName, pduFloorName, pduBuildingName)
			## Make sure that the device is in the dictionary
			if deviceKey not in hostOshDict.keys():
				debugPrint(2, '[getPowerRoutes] HOST with key <%s> not in dictionary! Skipping...' % deviceKey)
				continue
			## Make sure that the PDU is in the dictionary
			if pduKey not in pduOshDict.keys() and pduKey not in rppOshDict.keys():
				debugPrint(2, '[getPowerRoutes] PDU/RPP with key <%s> not in dictionary! Skipping...' % pduKey)
				continue
			debugPrint(2, '[getPowerRoutes] Creating USAGE link between HOST <%s> and PDU/RPP <%s>' % (deviceKey, pduKey))
			## Add USAGE link indicating power supply to OSHV
			pduOSH = pduOshDict[pduKey] or rppOshDict[pduKey]
			isPoweredByLink = modeling.createLinkOSH('usage', hostOshDict[deviceKey], pduOSH)
			isPoweredByLink.setAttribute('name', 'Is Powered By')
			resultVector.add(isPoweredByLink)
		return resultVector
	except:
		excInfo = logger.prepareJythonStackTrace('')
		logger.debug('[' + SCRIPT_NAME + ':getPowerRoutes] Exception: <%s>' % excInfo)
		pass
示例#39
0
def checkDiscoveryResources(mapingFilesListFileName, userExtDir, localFramework, intermediatesDir):
    try:
        initialMappingFileNameList = []
        mappingFileNameList = []

        ## Get mapping file list
        mappingFilesListFile = File(mapingFilesListFileName)
        if mappingFilesListFile.exists() and mappingFilesListFile.canRead():
            initialMappingFileNameList = getMappingFileNames(mapingFilesListFileName)
            if initialMappingFileNameList == None or len(initialMappingFileNameList) < 1:
                excInfo = ('No mapping files found in <%s>' % mapingFilesListFileName)
                localFramework.reportError(excInfo)
                logger.error(excInfo)
                return None
        else:
            excInfo = ('Error reading file <%s>' % mapingFilesListFileName)
            localFramework.reportError(excInfo)
            logger.error(excInfo)
            return None

        ## Make sure that at least one of the mapping files in the list above
        ## exists and is readable
        mappingFileExists = 'false'
        for mappingFileName in initialMappingFileNameList:
            mappingFileAbsolutePath = userExtDir + 'data\\' + mappingFileName + '.xml'
            mappingFile = File(mappingFileAbsolutePath)
            if mappingFile.exists() and mappingFile.canRead():
                debugPrint(4, '[' + SCRIPT_NAME + ':checkDiscoveryResources] Mapping file <%s> found!' % mappingFileAbsolutePath)
                mappingFileExists = 'true'
                ## Add file with path to mappingFileNameList
                #mappingFileNameList.append(mappingFileAbsolutePath)
                mappingFileNameList.append(mappingFileName)
            else:
                logger.info('Mapping file <%s> NOT found!' % mappingFileAbsolutePath)
        if mappingFileExists == 'false':
            excInfo = 'Error reading mapping file(s)!'
            localFramework.reportError(excInfo)
            logger.warn(excInfo)
            return None

        ## Make sure intermediates directory exists and is writable
        intermediatesDirectory = File(intermediatesDir)
        if intermediatesDirectory.exists() and intermediatesDirectory.canRead() and intermediatesDirectory.canWrite():
            debugPrint(5, '[' + SCRIPT_NAME + ':checkDiscoveryResources] Intermediates directory <%s> present and writable!' % intermediatesDir)
            ## Clean up intermediate XML directory
            ## TODO remove cleanUpDirectory(intermediatesDir)
        else:
            excInfo = ('Intermediates directory <%s> not found or is read-only' % intermediatesDir)
            localFramework.reportError(excInfo)
            logger.warn(excInfo)
            return None

        ## If we made it this far, all resources are good
        return mappingFileNameList
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME + ':checkDiscoveryResources] Exception: <%s>' % excInfo)
        pass
示例#40
0
def handleProcessToPortByLsof(USE_SUDO, localClient, procToPortDict):
    try:
        pidToPortMap = {}  # # We need a local pid to port map
        lsofCmd = 'lsof -n -P -i | grep -i listen 2>/dev/null'
        if USE_SUDO:
            lsofCmd = 'sudo ' + lsofCmd
        lsofStr = localClient.executeCmd(lsofCmd)
        lsofLines = dbconnect_utils.splitCommandOutput(lsofStr.strip())
        if lsofLines != None:
            for lsofLine in lsofLines:
                if len(lsofLine) < 1:
                    continue
                lsofLine = lsofLine.strip()
                m = re.search(
                    '\w+\s+(\d+)\s+\w+\s+\w+\s+IPv[4|6].+TCP\s+(\S+):(\d+)\s+\(\w+\)',
                    lsofLine)
                if (m):
                    pid = m.group(1).strip()
                    ipAddress = m.group(2).strip()
                    # # Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                    ipAddress = dbconnect_utils.fixIP(
                        ipAddress, localClient.getIpAddress())
                    serverPort = m.group(3).strip()
                    pidToPortMap[pid] = [ipAddress, serverPort]

            if pidToPortMap != None and len(pidToPortMap) > 0:
                for pid in pidToPortMap.keys():
                    if pid in procToPortDict.keys():
                        ipAddress = (pidToPortMap[pid])[0]
                        # # Skip loopback IPs
                        if re.search('127.0.0', ipAddress):
                            continue
                        serverPort = (pidToPortMap[pid])[1]
                        dbconnect_utils.debugPrint(
                            4, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnHPUX] Found port <%s:%s> for pid <%s>'
                            % (ipAddress, serverPort, pid))
                        (procToPortDict[pid]
                         )[dbconnect_utils.IP_INDEX] = ipAddress
                        (procToPortDict[pid]
                         )[dbconnect_utils.PORT_INDEX] = serverPort
            else:
                dbconnect_utils.debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnHPUX] No TCP port associated with PID ['
                    + pID + ']: ' + lsofLine)
        else:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnHPUX] Unable to make a process to port map using LSOF: '
                + lsofStr)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug(
            '[' + SCRIPT_NAME +
            ':getProcToPortDictOnHPUX] Unable to make a process to port map using LSOF: <%s>'
            % excInfo)
        pass
示例#41
0
def addOshFromDictToOshv(oshDict, oshVector):
    try:
        for OSH in oshDict.keys():
            oshVector.add(oshDict[OSH])
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':addOshFromDictToOshv] Exception: <%s>' % excInfo)
        pass
示例#42
0
def handleProcessToPortByPFile(USE_SUDO, localClient, procToPortDict):
    # # Use PFILES to map each process to a port and create a dictionary
    ############################################
    try:
        for pID in procToPortDict.keys():
            pFilesCmd = 'pfiles ' + pID + ' 2>/dev/null | grep "sockname: AF_INET"'
            if USE_SUDO:
                pFilesCmd = 'sudo ' + pFilesCmd
            pFilesStr = localClient.executeCmd(pFilesCmd)
            if len(pFilesStr) < 1:
                continue
            pFilesLines = dbconnect_utils.splitCommandOutput(pFilesStr.strip())
            if pFilesLines == None:
                dbconnect_utils.debugPrint(
                    4, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnSolaris] Error: Invalid output from pfiles: '
                    + pFilesStr)
                continue
            for pFilesLine in pFilesLines:
                pFilesLine = pFilesLine.strip()
                m = re.search(
                    '.+AF_INET\s+(\d+\.\d+\.\d+\.\d+)\s+port:\s*(\d+)',
                    pFilesLine)
                if re.search('AFINET6', pFilesLine):
                    m = re.search(
                        '.+AF_INET6.*:(\d+\.\d+\.\d+\.\d+)\s+port:\s*(\d+)',
                        pFilesLine)
                if (m) and m.group(2) != '0':
                    ipAddress = m.group(1).strip()
                    ## Skip loopback IPs
                    if re.search('127.0.0', ipAddress):
                        continue
                    ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                    ipAddress = dbconnect_utils.fixIP(
                        ipAddress, localClient.getIpAddress())
                    serverPort = m.group(2).strip()
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnSolaris] Adding port <%s:%s> for process <%s>'
                        % (ipAddress, serverPort,
                           (procToPortDict[pID]
                            )[dbconnect_utils.PROCESSNAME_INDEX]))
                    (procToPortDict[pID])[dbconnect_utils.IP_INDEX] = ipAddress
                    (procToPortDict[pID]
                     )[dbconnect_utils.PORT_INDEX] = serverPort
                else:
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnSolaris] No TCP port associated with PID ['
                        + pID + ']: ' + pFilesLine)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug(
            '[' + SCRIPT_NAME +
            ':getProcToPortDictOnSolaris] Unable to make a process to port map using pfiles: <%s>'
            % excInfo)
        pass
示例#43
0
def getAction(table_name, action, useMultiple=False):
    try:
        act = SNHelper.getAction(table_name, action)
        debugPrint(4, '[getAction] Got SN action <%s> for table <%s> and UCMDB action <%s>' % (act, table_name, action))
        return act
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[getAction] Exception: <%s>' % excInfo)
        pass
示例#44
0
def getServerName(localClient):
    try:
        returnHostName = None
        localClientType = localClient.getClientType()
        ## Try getting the servername from the OS
        if localClientType == 'telnet' or localClientType == 'ssh' or localClientType == 'ntadmin' or localClientType == 'uda':
            osHostName = localClient.executeCmd('hostname')
            if osHostName and len(osHostName) > 0:
                debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getServerName] Got OS hostname <%s> for SQL Server using SHELL client'
                    % osHostName)
                returnHostName = osHostName.strip()
        elif localClientType == 'wmi':
            wmiHostNameQuery = 'select Name from Win32_ComputerSystem'
            hostNameResultSet = localClient.executeQuery(wmiHostNameQuery)
            if hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(1)
                if osHostName and len(osHostName) > 0:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getServerName] Got OS hostname <%s> for SQL Server using WMI client'
                        % osHostName)
                    returnHostName = osHostName.strip()
        elif localClientType == 'snmp':
            hostNameResultSet = localClient.executeQuery(
                '1.3.6.1.2.1.1.5,1.3.6.1.2.1.1.6,string')
            while hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(2)
                if osHostName and len(osHostName) > 0:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getServerName] Got OS hostname <%s> for SQL Server using SNMP client'
                        % osHostName)
                    returnHostName = osHostName.strip()
        ## If we don't have a name yet, try DNS
        if returnHostName == None or returnHostName == '' or len(
                returnHostName) < 1:
            dnsName = netutils.getHostName(localClient.getIpAddress())
            if dnsName and len(dnsName) > 0 and dnsName.find('.'):
                debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getServerName] Got DNS name <%s> for SQL Server' %
                    dnsName)
                hostName = dnsName[:dnsName.find('.')]
                if hostName and len(hostName) > 0:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getServerName] Got host name <%s> for SQL Server from DNS name'
                        % hostName)
                    returnHostName = hostName
        return returnHostName
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME +
                   ':getServerName] Exception: <%s>' % excInfo)
        pass
def connectVfiler(wsConnection, vFiler):
    try:
        debugPrint(2, '[' + SCRIPT_NAME + ':connectVfiler] Connecting to vFiler <%s>' % (vFiler))
        if vFiler:
            wsConnection.setVfilerTunneling(vFiler)
            return wsConnection
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':connectVfiler] Exception: <%s>' % excInfo)
        pass
示例#46
0
def workOnIP(Framework, ip, ports):
    OPTION_UD_UNIQUE_ID = "UD_UNIQUE_ID"
    us = UDAStatus(ip)
    us.alive = True
    alivePort = None
    logger.debug("IP %s alive:%s" % (ip, us.alive))
    if us.alive:
        for port in ports:
            us.portAlive = detectPortAvailable(ip, port)
            if us.portAlive:
                alivePort = port
                break

        logger.debug("Port alive %s on IP:Port %s:%s" %
                     (us.portAlive, us.ip, str(alivePort)))
        #set computerName by ping -a
        us.computerName = detectHostnameWithPing(ip)
        if us.portAlive:
            client = detectUDAAvailable(Framework, ip)
            if client:
                us.udaAlive = True
                logger.debug("UDA alive %s on IP %s" % (us.udaAlive, us.ip))
                try:
                    us.isDDMI = detectDDMIAgent(Framework, client, us)
                    logger.debug("UDA is DDMI %s on IP %s" %
                                 (us.isDDMI, us.ip))
                    if not us.isDDMI:
                        us.isNative = True  #detectUDANative(Framework, client, us)
                        logger.debug("UDA is native %s on IP %s" %
                                     (us.isNative, us.ip))
                        us.isFIPSEnabled = detectFIPSMode(client)

                        if isDupUDUniqueId(us.UDUniqueId):
                            logger.debug("old uuid ", us.UDUniqueId)
                            uduid = UUID.randomUUID()
                            logger.debug("generate new uuid ", uduid)
                            options = HashMap()
                            options.put(OPTION_UD_UNIQUE_ID, str(uduid))
                            client.setOptionsMap(options)
                            clientOptions = client.getOptionsMap()
                            uduid = clientOptions.get(OPTION_UD_UNIQUE_ID)
                            logger.debug("get new uuid ", uduid)
                            us.UDUniqueId = uduid

                except:
                    msg = logger.prepareJythonStackTrace('')
                    errormessages.resolveAndReport(
                        msg, ClientsConsts.ICMP_PROTOCOL_NAME, Framework)
                    pass
                finally:
                    try:
                        client.close()
                    except:
                        pass
    return us
示例#47
0
def doQuery(dbQueryClient, query):
    try:
        resultSet = None
        try:
            resultSet = dbQueryClient.executeQuery(query)
        except:
            logger.errorException('Failed executing query: <', query, '> on <', dbQueryClient.getIpAddress(), '> Exception:')
        return resultSet
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':doQuery] Exception: <%s>' % excInfo)
        pass
示例#48
0
def getIpSubnetDict(localDbClient, ipAddressList, netDeviceID,
                    netDeviceElementID, netDeviceName):
    try:
        ipSubnetDict = {}
        ipSubnetQuery = 'SELECT IPAddress, SubnetMask FROM dba.IPProtocolEndPoint WHERE NetworkElementId=%s' % netDeviceElementID
        ipSubnetResultSet = ciscoworks_utils.doQuery(localDbClient,
                                                     ipSubnetQuery)

        ## Return if query returns no results
        if ipSubnetResultSet == None:
            logger.info(
                '[' + SCRIPT_NAME +
                ':getIpSubnetDict] No IP Addresses found for Net Device <%s>' %
                netDeviceName)
            return None

        ## We have query results!
        while ipSubnetResultSet.next():
            ipAddress = ciscoworks_utils.getStringFromResultSet(
                ipSubnetResultSet, 1)
            subnetMask = ciscoworks_utils.getStringFromResultSet(
                ipSubnetResultSet, 2)
            if ipAddress:
                ## Discard duplicate IPs
                if ipAddress in ipAddressList:
                    ciscoworks_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getIpSubnetDict] Duplicate IP address <%s> on Network Device <%s> with ID <%s>!! Discarding...'
                        % (ipAddress, netDeviceName, netDeviceElementID))
                    continue
                else:
                    ipAddressList.append(ipAddress)
                ## Create IP OSH
                if subnetMask:
                    ciscoworks_utils.debugPrint(
                        2, '[' + SCRIPT_NAME +
                        ':getIpSubnetDict] Got IP <%s> with subnet mask <%s> for Net Device <%s> with ID <%s>'
                        % (ipAddress, subnetMask, netDeviceName,
                           netDeviceElementID))
                    ipSubnetDict[ipAddress] = netutils.parseNetMask(subnetMask)
                else:
                    ciscoworks_utils.debugPrint(
                        2, '[' + SCRIPT_NAME +
                        ':getIpSubnetDict] Got IP <%s> without subnet mask for Net Device <%s> with ID <%s>'
                        % (ipAddress, netDeviceName, netDeviceElementID))
                    ipSubnetDict[ipAddress] = ''

        return ipSubnetDict
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME +
                    ':getIpSubnetDict] Exception: <%s>' % excInfo)
        pass
示例#49
0
 def getSqlFiles(self, oshv, dbmap, hostId, users):
     try:
         self.getSqlFilesFromMaster(oshv, dbmap, hostId, users)
     except:
         exInfo = logger.prepareJythonStackTrace('')
         logger.debug("Failed to get sql file from master. ", exInfo)
         logger.debug("Collecting the details from each user databases.")
         itr = dbmap.entrySet().iterator()
         while (itr.hasNext()):
             entry = itr.next()
             dbName = entry.getKey()
             dbObject = entry.getValue()
             self.getSqlFilesByDBName(oshv, dbName, dbObject, hostId)
示例#50
0
def doQuery(oracleQueryClient, query):
    'Perform a SQL query using the given connection and return a result set'
    try:
        resultSet = None
        try:
            resultSet = oracleQueryClient.executeQuery(query)
        except:
            logger.errorException('Failed executing query: <', query, '> on <', oracleQueryClient.getIpAddress(), '> Exception:')
        return resultSet
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':doQuery] Exception: <%s>' % excInfo)
        pass
示例#51
0
def connectVfiler(wsConnection, vFiler):
    try:
        debugPrint(
            2, '[' + SCRIPT_NAME +
            ':connectVfiler] Connecting to vFiler <%s>' % (vFiler))
        if vFiler:
            wsConnection.setVfilerTunneling(vFiler)
            return wsConnection
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME +
                    ':connectVfiler] Exception: <%s>' % excInfo)
        pass
示例#52
0
def populateOSH(theOSH, attrDict):
    try:
        for attrName in attrDict.keys():
            debugPrint(5, '[' + SCRIPT_NAME + ':populateOSH] Got attrName <%s> with value <%s>' % (attrName, attrDict[attrName]))
            if not attrDict[attrName] or str(attrDict[attrName]).lower() == 'null':
                debugPrint(5, '[' + SCRIPT_NAME + ':populateOSH] Got empty value for attribute <%s>' % attrName)
                continue
            else:
                theOSH.setAttribute(attrName, attrDict[attrName])
        return None
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':populateOSH] Exception: <%s>' % excInfo)
        pass
示例#53
0
def processVlanPortMap(portVlanIdMap):
    try:
        returnOSHV = ObjectStateHolderVector()
        if portVlanIdMap:
            for portVlanIdMapKey in portVlanIdMap.keys():
                vlanNameAndId = portVlanIdMapKey.split(':;:')
                vlanName = vlanNameAndId[0]
                vlanID = vlanNameAndId[1]
                ## Build VLAN OSH
                if vlanName and vlanName != 'N/A' and vlanID and vlanID != '-1' and type(
                        eval(vlanID)) == type(1):
                    ## Get a list of port IDs from the port OSH list in this map
                    portOshList = portVlanIdMap[portVlanIdMapKey]
                    portIdList = []
                    for portOSH in portOshList:
                        portIdList.append(
                            str(portOSH.getAttributeValue('port_index')))
                    portIdList.sort()

                    ciscoworks_utils.debugPrint(
                        2, '[' + SCRIPT_NAME +
                        ':processVlanPortMap] Got VLAN <%s> with <%s> ports, total VLANs <%s>'
                        %
                        (portVlanIdMapKey, len(portIdList), len(portVlanIdMap))
                    )
                    vlanUniqueID = str(hash(':'.join(portIdList)))
                    if not vlanUniqueID:
                        vlanUniqueID = 1
                    #vlanOSH = modeling.createVlanOsh(vlanID, None, portIdList)
                    vlanOSH = ObjectStateHolder('vlan')
                    ciscoworks_utils.populateOSH(
                        vlanOSH, {
                            'name': vlanName,
                            'vlan_aliasname': vlanName,
                            'vlan_id': int(vlanID),
                            'vlan_unique_id': vlanUniqueID
                        })
                    returnOSHV.add(vlanOSH)

                    ## Add a member link between this VLAN and all ports related to it
                    for portOSH in portOshList:
                        returnOSHV.add(
                            modeling.createLinkOSH('membership', vlanOSH,
                                                   portOSH))
        return returnOSHV
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME +
                    ':processVlanPortMap] Exception: <%s>' % excInfo)
        pass