Example #1
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    logger.debug('Start nmap_osfingerprint.py')
    ip = Framework.getDestinationAttribute('ip_address')
    timeout = Framework.getParameter('nmap_host_timeout')
    if not str(timeout).isdigit():
        msg = "Timeout parameter value must be a digit"
        logger.debug(msg)
        errormessages.resolveAndReport(msg,
                                       ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME,
                                       Framework)
        return OSHVResult

    timeout = int(timeout) * 1000
    scanKnownPortsOnly = Boolean.parseBoolean(
        Framework.getParameter('scan_known_ports_only'))
    portstoscan = Framework.getParameter('scan_these_ports_only')
    doServiceFingerprints = Boolean.parseBoolean(
        Framework.getParameter('Perform_Port_Fingerprints'))
    createApp = Boolean.parseBoolean(
        Framework.getParameter('Create_Application_CI'))
    discoverOsName = Boolean.parseBoolean(
        Framework.getParameter('discover_os_name'))
    nmapLocation = Framework.getParameter('nmap_location')
    #discover_UDP_Ports	= int(Framework.getParameter('Discover_UDP_Ports'))
    discoverUdpPorts = 0

    agent_root_dir = CollectorsParameters.BASE_PROBE_MGR_DIR
    agent_ext_dir = agent_root_dir + CollectorsParameters.getDiscoveryResourceFolder(
    ) + CollectorsParameters.FILE_SEPARATOR
    tmp_file_name = agent_ext_dir + string.replace(
        ip, '.', '_') + time.strftime("%H%M%S", time.gmtime(
            time.time())) + 'nmap.xml'

    syncNmapPortConfigFile(agent_root_dir)

    logger.debug('temp file for storing nmap results: ', tmp_file_name)
    try:
        client = Framework.createClient(
            ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
        try:
            performNmapDiscover(client, ip, tmp_file_name, timeout,
                                agent_ext_dir, scanKnownPortsOnly, portstoscan,
                                doServiceFingerprints, discoverUdpPorts,
                                nmapLocation)
            if os.path.exists(tmp_file_name):
                logger.debug('start processing the nmap results')
                processNmapResult(tmp_file_name, OSHVResult, discoverOsName,
                                  doServiceFingerprints, createApp, Framework)
            else:
                raise ValueError, 'Error nmap result file is missing: %s' % tmp_file_name
        finally:
            client.close()
            File(tmp_file_name).delete()
    except Exception, e:
        msg = str(e.getMessage())
        logger.debug(msg)
        errormessages.resolveAndReport(msg,
                                       ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME,
                                       Framework)
def write_ordered_variables(program_name,
                            variable_map,
                            file_path,
                            append=False):
    """
    Write variables to file while preserving order of the variables.
    :param program_name: name of the calling program
    :param variable_map: map or variable properties to write to file
    :param file_path: the file to which to write the properties
    :param append: defaults to False. Append properties to the end of file
    :raises VariableException if an error occurs while storing the variables in the file
    """
    _method_name = 'write_ordered_variables'
    _logger.entering(program_name,
                     file_path,
                     append,
                     class_name=_class_name,
                     method_name=_method_name)
    pw = None
    try:
        pw = PrintWriter(FileOutputStream(File(file_path), Boolean(append)),
                         Boolean('true'))
        for key, value in variable_map.iteritems():
            formatted = '%s=%s' % (key, value)
            pw.println(formatted)
        pw.close()
    except IOException, ioe:
        _logger.fine('WLSDPLY-20007', file_path, ioe.getLocalizedMessage())
        ex = exception_helper.create_variable_exception(
            'WLSDPLY-20007', file_path, ioe.getLocalizedMessage(), error=ioe)
        _logger.throwing(ex, class_name=_class_name, method_name=_method_name)
        if pw is not None:
            pw.close()
        raise ex
Example #3
0
 def getUsers(self, domainName):
     ''' Get users for specified domain name.
     Information about users contains name, description, UID, full name, lock status,
     disabled or enabled status.
     str -> list(User)
     @command: SELECT Description, Disabled, Domain, FullName, Lockout, Name, SID FROM Win32_UserAccount  WHERE Domain = '<domainName>'
     @raise Exception: if WMI query failed
     '''
     users = []
     builder = self._provider.getBuilder(
         'Win32_UserAccount').addWmiObjectProperties(
             'Name', 'FullName', 'Description', 'SID', 'Disabled', 'Domain',
             'Lockout')
     builder.addWhereClause("Domain = '%s'" % domainName)
     accounts = self._provider.getAgent().getWmiData(builder,
                                                     timeout=180000)
     for account in accounts:
         user = User(account.Name,
                     description=account.Description,
                     uid=account.SID)
         user.fullName = account.FullName
         user.isDisabled = Boolean.valueOf(account.Disabled)
         user.domain = account.Domain
         user.isLocked = Boolean.valueOf(account.Lockout)
         users.append(user)
     return users
Example #4
0
    def test_cast(self):
        from java.lang import Boolean, Object
        b = Boolean(True)
        b_Object = cast(Object, b)
        self.assertIsNot(b, b_Object)
        self.assertEqual(b, b_Object)
        self.assertIs(Boolean.getClass(), b.getClass())
        self.assertIs(Boolean.getClass(), b_Object.getClass())
        self.assertIsNot(Object.getClass(), b_Object.getClass())
        self.assertIs(b_Object, cast(Object, b))
        self.assertIs(b, cast(Boolean, b_Object))

        for obj in [Boolean, "Ljava/lang/Boolean;"]:
            with self.subTest(obj=obj):
                with self.assertRaisesRegex(TypeError, "cannot create java.lang.Boolean "
                                            "proxy from java.lang.Object instance"):
                    cast(obj, Object())

        with self.assertRaisesRegex(jclass("java.lang.NoClassDefFoundError"),
                                    "java.lang.Nonexistent"):
            cast("Ljava/lang/Nonexistent;", Object())

        with self.assertRaisesRegex(ValueError, "Invalid JNI signature: 'java.lang.Object'"):
            cast("java.lang.Object", Object())

        for obj in [0, True, None, int, str]:
            with self.subTest(obj=obj):
                with self.assertRaisesRegex(TypeError, f"{obj!r} is not a Java type"):
                    cast(obj, Object())
Example #5
0
def stringToBoolean(value):
    value = value.strip()
    if value.lower() == 'yes' or value.lower() == 'true' or value.lower(
    ) == '1':
        return Boolean('true')
    else:
        return Boolean('false')
Example #6
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)
 def start(self):
     "start enabler"
     
     logger.info("Enter start")
     copyContainerEnvironment()
     self.__initOptions()
      
     if self.__composeFile:
         self.__composeCreate()
         self.__composeStart()
         self.__composePs()
     else:
         reuseContainer = Boolean.parseBoolean(getVariableValue("REUSE_DOCKER_CONTAINER", "false"))
         reuseImage = Boolean.parseBoolean(getVariableValue("REUSE_DOCKER_IMAGE", "true"))
     
         llen = len(self.__dockerContainerName)
         for index in range(llen):
             if reuseContainer and self.__containerExists(index):
                 self.__start(index)
             elif reuseImage and self.__imageExists(index):
                 self.__run(index)
             elif listItem(self.__dockerContext, index):
                 self.__build(index)
                 self.__run(index)
             else:
                 self.__pull(index)
                 self.__run(index)
         
             while index < (llen - 1):
                 logger.info("Waiting for container to start:" + listItem(self.__dockerContainerName, index))
                 time.sleep(float(self.__startInterval))
                 if self.__isContainerRunning(index):
                     break
   
     logger.info("Exit start")
Example #8
0
    def start(self):
        "start enabler"

        logger.info("Enter start")
        copyContainerEnvironment()
        self.__initOptions()

        reuseContainer = Boolean.parseBoolean(
            getVariableValue("REUSE_DOCKER_CONTAINER", "false"))
        reuseImage = Boolean.parseBoolean(
            getVariableValue("REUSE_DOCKER_IMAGE", "true"))

        llen = len(self.__dockerContainerName)
        for index in range(llen):
            if reuseContainer and self.__containerExists(index):
                self.__start(index)
            elif reuseImage and self.__imageExists(index):
                self.__run(index)
            elif listItem(self.__dockerContext, index):
                self.__build(index)
                self.__run(index)
            else:
                self.__pull(index)
                self.__run(index)

            while index < (llen - 1):
                logger.info("Waiting for container to start:" +
                            listItem(self.__dockerContainerName, index))
                time.sleep(float(self.__startInterval))
                if self.__isContainerRunning(index):
                    break

        logger.info("Exit start")
Example #9
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    port = entity.WeakNumeric(int)
    port.set(Framework.getDestinationAttribute('port'))
    version = Framework.getDestinationAttribute('version')

    resultVector = ObjectStateHolderVector()
    isAppResourcesDiscoveryEnabled = Boolean.valueOf(
        Framework.getParameter('discoverAppResources'))
    isJMSResourcesDiscoveryEnabled = Boolean.valueOf(
        Framework.getParameter('discoverJMSResources'))
    discoverDeployedOnlyApplications = Boolean.valueOf(
        Framework.getParameter("discoverDeployedOnlyApplications"))
    protocolType = (Framework.getDestinationAttribute('protocol')
                    or ClientsConsts.HTTP_PROTOCOL_NAME)

    properties = Properties()
    properties.put(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT,
                   str(port.value()))
    properties.put(AgentConstants.VERSION_PROPERTY, version)
    properties.put(AgentConstants.PROP_WEBLOGIC_PROTOCOL, protocolType)

    platform = jee.Platform.WEBLOGIC

    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Example #10
0
class tableModel(DefaultTableModel):
    columnNames = ['First Name', 'Last Name', 'Married?']
    dataType = [String, String, Boolean]
    data = [['Rand', "al'Thor", Boolean(1)], ['Egwene', "al'Vere",
                                              Boolean(0)],
            ['Matrim', 'Cauthon', Boolean(1)],
            ['Perrin', 'Aybara', Boolean(1)],
            ['Moiraine', 'Damodred', Boolean(0)]]

    def getColumnCount(self):
        return len(self.columnNames)

    def getRowCount(self):
        return len(self.data)

    def getColumnName(self, col):
        return self.columnNames[col]

    def getValueAt(self, row, col):
        return self.data[row][col]

    def getColumnClass(self, col):
        return self.dataType[col]

    def isCellEditable(self, row, col):
        return col > 1

    def setValueAt(self, value, row, col):
        try:
            self.data[row][col] = self.dataType[col](value)
        except:
            Type = str(self.dataType[col]).split('.')[-1]
            print '\nError: invalid %s value ignored: "%s"' % (Type, value),
        self.fireTableCellUpdated(row, col)
Example #11
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    port = entity.WeakNumeric(int)
    port.set(Framework.getDestinationAttribute('port'))
    version = Framework.getDestinationAttribute('version')

    resultVector = ObjectStateHolderVector()
    isAppResourcesDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverAppResources'))
    isJMSResourcesDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverJMSResources'))
    discoverDeployedOnlyApplications = Boolean.valueOf(Framework.getParameter("discoverDeployedOnlyApplications"))
    protocolType = (Framework.getDestinationAttribute('protocol') or
                    ClientsConsts.HTTP_PROTOCOL_NAME)

    properties = Properties()
    properties.put(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT, str(port.value()))
    properties.put(AgentConstants.VERSION_PROPERTY, version)
    properties.put(AgentConstants.PROP_WEBLOGIC_PROTOCOL, protocolType)

    platform = jee.Platform.WEBLOGIC

    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Example #12
0
 def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):
     if roundness == 0:
         p = CanvasContext.rect(self, x, y, width, height, Boolean(draw))
     else:
         rw = roundness * width * 0.5
         rh = roundness * height * 0.5
         p = CanvasContext.rect(self, x, y, width, height, rw, rh, Boolean(draw))
     self._setAttributesFromKwargs(p, **kwargs)
     return p
Example #13
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    client = None
    layer2_connections_cdp = None
    layer2_connections_lldp = None
    try:
        try:
            client = Framework.createClient()
        except:
            errMsg = 'Exception while creating %s client: %s' % (
                ClientsConsts.SNMP_PROTOCOL_NAME, sys.exc_info()[1])
            errormessages.resolveAndReport(str(sys.exc_info()[1]),
                                           ClientsConsts.SNMP_PROTOCOL_NAME,
                                           Framework)
            logger.debugException(errMsg)
        else:
            host_id = Framework.getDestinationAttribute('hostId')
            discover_cdp_mib = Boolean.parseBoolean(
                Framework.getParameter('discoverCdpMib'))
            discover_lldp_mib = Boolean.parseBoolean(
                Framework.getParameter('discoverLldpMib'))
            local_device_discoverer = LocalDeviceDiscoverer(client, host_id)
            local_devices = local_device_discoverer.get_local_devices()
            if not local_devices or len(local_devices) == 0:
                logger.reportError('Failed to get local device info')

            if discover_cdp_mib:
                cdp_discoverer = CdpDiscoverer(client)
                remote_devices_cdp = cdp_discoverer.get_remote_devices()
                if remote_devices_cdp:
                    layer2_connections_cdp = get_layer2_connections(
                        local_devices, remote_devices_cdp)
                    for layer2_connection in layer2_connections_cdp:
                        OSHVResult.addAll(
                            build_layer2_connection(layer2_connection))

            if discover_lldp_mib:
                lldp_discoverer = LldpDiscoverer(client)
                remote_devices_lldp = lldp_discoverer.get_remote_devices()
                if remote_devices_lldp:
                    layer2_connections_lldp = get_layer2_connections(
                        local_devices, remote_devices_lldp)
                    for layer2_connection in layer2_connections_lldp:
                        OSHVResult.addAll(
                            build_layer2_connection(layer2_connection))

            if (not layer2_connections_cdp or len(layer2_connections_cdp)
                    == 0) and (not layer2_connections_lldp
                               or len(layer2_connections_lldp) == 0):
                logger.reportError('No data collected')

    finally:
        if client != None:
            client.close()
    return OSHVResult
Example #14
0
    def initializeServices(self):
        self.discoverDependLinks = 1
        self.shouldCountClients = 0
        self.updateUtilizationInfo = Boolean.parseBoolean(self.getParameterValue('updateUtilizationInfo'))
        self.onlyHostDependLinks = Boolean.parseBoolean(self.getParameterValue('onlyHostDependLinks'))
        self.ignoreUnackedTcpConn = Boolean.parseBoolean(self.getParameterValue('ignoreUnackedTcpConn'))

        self.minimalClients = 0
        self.minimalOctets = 0
        self.minimalPackets = 0
Example #15
0
def str_bool(bool_value):
    """
    Return string representation of the integer boolean value.
    :param bool_value: to return in string format
    :return: string boolean representation or None if a valid boolean value was not passed
    """
    if bool_value is True:
        return Boolean('true').toString()
    elif bool_value is False:
        return Boolean('false').toString()
    return None
def DiscoveryMain(Framework):
    properties = Properties()

    SITE_ID = Framework.getDestinationAttribute('SITE_ID')
    instance_number = Framework.getDestinationAttribute('instance_number')
    connection_client = Framework.getDestinationAttribute('connection_client')
    logger.debug('Connecting to a SAP instance number:', str(instance_number))
    properties.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_SYSNUMBER, instance_number)

    if (connection_client is not None) and (connection_client != 'NA'):
        logger.debug('Connecting to a SAP system with client:', str(connection_client))
        properties.setProperty(Protocol.SAP_PROTOCOL_ATTRIBUTE_CLIENT, connection_client)
    discoverScenarioProcesses = Boolean.parseBoolean(Framework.getParameter('discoverScenarioProcesses'))
    GET_PROCESS_STEPS = Boolean.parseBoolean(Framework.getParameter('getProcessSteps'))
    reportCIsInChunks = Boolean.parseBoolean(Framework.getParameter('reportCIsInChunks'))

    errormsg = ''
    client = None
    try:
        try:
            client = Framework.createClient(properties)
            solman = saputils.SapSolman(client)
        except (NoClassDefFoundError, MissingJarsException, ExceptionInInitializerError):
            errormsg = 'SAP drivers are missing'
            logger.debugException(errormsg)
        except:
            errormsg = 'Connection failed'
            logger.debugException(errormsg)
        else:
            try:
                sVector, sysToOshPairs = discoverSystems(solman)
                Framework.sendObjects(sVector)
                sVector.clear()
                sysNames = [system.getName() for system, _ in sysToOshPairs]
                sys_name_to_system = {}
                for system, _ in sysToOshPairs:
                    sys_name_to_system[system.getName()] = system

                component2system = logicalComponents(sysNames, solman)
                businessProcesses(Framework, solman, component2system,
                                  sys_name_to_system, SITE_ID, GET_PROCESS_STEPS, reportCIsInChunks,
                                  discoverScenarioProcesses)
            except:
                strmsg = str(sys.exc_info()[1])
                if (strmsg.upper().find('TABLE_NOT_AVAILABLE') > -1):
                    errmsg = 'No solution manager found'
                    logger.debugException(errmsg)
                    Framework.reportError(errmsg)
                else:
                    # unknown exception caught
                    raise
    except JException, ex:
        ex_info = ex.getMessage()
        errormessages.resolveAndReport(ex_info, 'SAP JCO', Framework)
Example #17
0
 def text(self, txt, x, y, width=0, height=0, outline=False, draw=True, **kwargs):
     if outline:
         t = CanvasContext.text(self, unicode(txt), x, y, width, height, Boolean(False))
         p = t.path
         self._setAttributesFromKwargs(p, **kwargs)
         if draw:
             self.addPath(p)
         return p
     else:
         t = CanvasContext.text(self, unicode(txt), x, y, width, height, Boolean(draw))
         self._setAttributesFromKwargs(t, **kwargs)
         return t
def isStampEnabled(Framework, ip):
    from java.lang import Boolean

    enableStampingParameter = Framework.getParameter('enableStamping')
    onlyStampingClientParameter = Framework.getParameter('onlyStampingClient')
    logger.debug("Parameter for enableStamping:", enableStampingParameter)
    logger.debug("Parameter for onlyStampingClient:", onlyStampingClientParameter)
    enableStamping = Boolean.parseBoolean(enableStampingParameter)
    onlyStampingClient = Boolean.parseBoolean(onlyStampingClientParameter)
    isClientIP = isClientTypeIP(ip)

    return enableStamping and (not onlyStampingClient or isClientIP)
Example #19
0
def isStampEnabled(Framework, ip):
    from java.lang import Boolean

    enableStampingParameter = Framework.getParameter('enableStamping')
    onlyStampingClientParameter = Framework.getParameter('onlyStampingClient')
    logger.debug("Parameter for enableStamping:", enableStampingParameter)
    logger.debug("Parameter for onlyStampingClient:",
                 onlyStampingClientParameter)
    enableStamping = Boolean.parseBoolean(enableStampingParameter)
    onlyStampingClient = Boolean.parseBoolean(onlyStampingClientParameter)
    isClientIP = isClientTypeIP(ip)

    return enableStamping and (not onlyStampingClient or isClientIP)
def _obtainParams(framework):
    zoneNameList = framework.getParameter("zoneList")
    splitRegexp = re.compile("[,;]")
    isNonEmptyString = lambda s: s and s.strip()
    zoneNameList = filter(isNonEmptyString, map(string.strip, splitRegexp.split(zoneNameList)))

    from java.lang import Boolean

    includeOutscopeIPs = framework.getParameter("includeOutscopeIPs")
    includeOutscopeIPs = Boolean.valueOf(includeOutscopeIPs)

    reportBrokenAliases = framework.getParameter("reportBrokenAliases")
    reportBrokenAliases = Boolean.valueOf(reportBrokenAliases)
    return zoneNameList, includeOutscopeIPs, reportBrokenAliases
    def initializeServices(self):
        self.updateUtilizationInfo = 1
        self.discoverDependLinks = Boolean.parseBoolean(self.getParameterValue('discoverDependLinks'))
        self.onlyHostDependLinks = 0
        self.ignoreUnackedTcpConn = 0
        self.shouldCountClients = 1

        self.discoverIP = self.Framework.getDestinationAttribute('ip_address')
        self.hostId = self.Framework.getDestinationAttribute('hostId')
        self.minimalClients = Integer.parseInt(self.Framework.getParameter('minClients'))
        self.minimalOctets = Integer.parseInt(self.Framework.getParameter('minOctets'))
        self.minimalPackets = Integer.parseInt(self.Framework.getParameter('minPackets'))
        self.protocols = self.Framework.getParameter('protocols')
        self.disregardListenPorts = Boolean.parseBoolean(self.getParameterValue('disregardListenPorts'))
Example #22
0
def _obtainParams(framework):
    zoneNameList = framework.getParameter("zoneList")
    splitRegexp = re.compile('[,;]')
    isNonEmptyString = lambda s: s and s.strip()
    zoneNameList = filter(isNonEmptyString,
                          map(string.strip, splitRegexp.split(zoneNameList)))

    from java.lang import Boolean
    includeOutscopeIPs = framework.getParameter('includeOutscopeIPs')
    includeOutscopeIPs = Boolean.valueOf(includeOutscopeIPs)

    reportBrokenAliases = framework.getParameter('reportBrokenAliases')
    reportBrokenAliases = Boolean.valueOf(reportBrokenAliases)
    return zoneNameList, includeOutscopeIPs, reportBrokenAliases
Example #23
0
    def __activate__(self, context):
        self.velocityContext = context
        self.services = context["Services"]
        self.request = context["request"]
        self.response = context["response"]
        self.contextPath = context["contextPath"]
        self.formData = context["formData"]
        self.page = context["page"]

        self.uaActivated = False
        useDownload = Boolean.parseBoolean(self.formData.get("download", "true"))
        self.__isPreview = Boolean.parseBoolean(self.formData.get("preview", "false"))
        self.__previewPid = None
        self.__hasPid = False

        uri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
        matches = re.match("^(.*?)/(.*?)/(?:(.*?)/)?(.*)$", uri)
        if matches and matches.group(3):
            oid = matches.group(3)
            pid = matches.group(4)

            self.__metadata = JsonConfigHelper()
            self.__object = self.__getObject(oid)
            self.__oid = oid

            # If we have a PID
            if pid:
                self.__hasPid = True
                if useDownload:
                    # Download the payload to support relative links
                    download = DownloadData()
                    download.__activate__(context)
                else:
                    # Render the detail screen with the alternative preview
                    self.__readMetadata(oid)
                    self.__previewPid = pid
            # Otherwise, render the detail screen
            else:
                self.__readMetadata(oid)
                self.__previewPid = self.getPreview()

            if self.__previewPid:
                self.__previewPid = URLEncoder.encode(self.__previewPid, "UTF-8")
        else:
            # require trailing slash for relative paths
            q = ""
            if self.__isPreview:
                q = "?preview=true"
            self.response.sendRedirect("%s/%s/%s" % (self.contextPath, uri, q))
Example #24
0
def shouldInstallScanner(scannerPlatformConfig, Framework, shell):
	shouldInstall = 0
	#staring to check scanner version on remote machine
	isUpgradeAllowed = Boolean.parseBoolean(Framework.getParameter('IsScannerUpgradeAllowed'))
	logger.debug('Parameter isUpgradeAllowed:', isUpgradeAllowed)
	IsDowngradeAllowed = Boolean.parseBoolean(Framework.getParameter('IsScannerDowngradeAllowed'))
	logger.debug('Parameter IsDowngradeAllowed:', IsDowngradeAllowed)

	if isUpgradeAllowed and IsDowngradeAllowed:
		logger.debug('Upgrade and Downgrade allowed, installing scanner in any case')
		shouldInstall = 1
	else:
		remoteScannerVersion = Framework.getDestinationAttribute('scannerVersion')
		if (remoteScannerVersion is None) or (len(str(remoteScannerVersion)) == 0) or (str(remoteScannerVersion) == 'NA'):
			logger.debug('Remote scanner version is unavailable, going to execute scanner upgrade')
			shouldInstall = 1
		else:
			logger.debug('Scanner already found on remote machine')
			installerFileName = scannerPlatformConfig.getScannerExecutable()
			installerVersioninstallerXmlFilePath = CollectorsParameters.PROBE_MGR_RESOURCES_DIR + 'ud_scanners' + str(File.separator) + installerFileName + '-version.xml'
			logger.debug('Checking installer version in file ', installerVersioninstallerXmlFilePath)
			installerXmlFile = File(installerVersioninstallerXmlFilePath)
			if installerXmlFile.exists() and installerXmlFile.isFile():
				installerVersion = getInstallerVersion(installerXmlFile, Framework)
				logger.debug('Current scanner version ', installerVersion)
				m = re.search('([\d\.]+) build ([\d]+)', remoteScannerVersion)
				if m:
					remoteScannerVersion = m.group(1)+'.'+m.group(2)
					logger.debug('Remote scanner version ', remoteScannerVersion)
					if compareVersions(installerVersion, remoteScannerVersion) > 0:
						if isUpgradeAllowed:
							logger.debug('Upgrade should be perfomed')
							shouldInstall = 1
						else:
							logger.debug('Upgrade is not allowed')
					elif compareVersions(installerVersion, remoteScannerVersion) < 0:
						if IsDowngradeAllowed:
							logger.debug('Downgrade should be perfomed')
							shouldInstall = 1
						else:
							logger.debug('Downgrade is not allowed')
				else:
					logger.debug('Scanner should be installed')
					shouldInstall = 1
			else:
				if isUpgradeAllowed:
					logger.debug('Going to upgrade scanner, version file not exists:', installerVersioninstallerXmlFilePath)
					shouldInstall = 1
	return shouldInstall
Example #25
0
    def __composeDown(self):

        logger.info("Enter docker compose down")
        try:
            project = getVariableValue("DOCKER_COMPOSE_PROJECT",
                                       self.__compName)
            cmdlist = [
                self.__dockerCompose, "--file", self.__composeFile,
                "--project-name", project, "down"
            ]
            removeImage = Boolean.parseBoolean(
                getVariableValue("REMOVE_DOCKER_IMAGE", "false"))

            if removeImage:
                cmdlist.extend(["--rmi", "all"])

            removeOptions = getVariableValue("DOCKER_REMOVE_OPTIONS")
            if removeOptions and removeOptions.find("--volumes=true") >= 0:
                cmdlist.append("--volumes")

            logger.info("Executing:" + list2str(cmdlist))
            os.environ["DOCKER_HOST"] = "tcp://" + self.__dockerAddr
            os.environ["COMPOSE_HTTP_TIMEOUT"] = "300"
            self.__lock()
            retcode = call(cmdlist)
            logger.info("Return code:" + str(retcode))
        except:
            type, value, traceback = sys.exc_info()
            logger.severe("composeDown error:" + ` value `)
            raise
        finally:
            self.__unlock()

        logger.info("Exit docker compose down")
Example #26
0
 def __activate__(self, context):
     self.services = context["Services"]
     self.page = context["page"]
     self.formData = context["formData"]
     self.sessionState = context["sessionState"]
     self.request = context["request"]
     self.pageName = context["pageName"]
     
     self.__portal = context["page"].getPortal()
     sessionNav = self.__portal.get("portal/use-session-navigation", "true")
     self.__useSessionNavigation = Boolean.parseBoolean(sessionNav)
     self.__result = JsonConfigHelper()
     if self.__useSessionNavigation:
         self.__pageNum = self.sessionState.get("pageNum", 1)
     else:
         self.__pageNum = 1
     self.__selected = ArrayList()
     self.__fqParts = []
     self.__searchField = self.formData.get("searchField", "full_text")
     
     if self.__portal.getName() != self.lastPortalId:
         self.sessionState.remove("fq")
         self.sessionState.remove("pageNum")
         self.__pageNum = 1
         self.lastPortalId =  self.__portal.getName()
     
     self.__search()
Example #27
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    logger.info ("Starting IMS Discovery")
    DiscoverIMSDB = Boolean.parseBoolean(Framework.getParameter('DiscoverIMSDB'))

    # create LPAR node from the ID passed in
    hostId = Framework.getDestinationAttribute(PARAM_HOST_ID)
    lparOsh = None

    if eview_lib.isNotNull(hostId):
        lparOsh = modeling.createOshByCmdbIdString('host_node', hostId)

    ls = eview_lib.EvShell(Framework)
    IMSSubSysDict = getIMSSubSys(ls, lparOsh)
    OSHVResult.addAll(getIMSActRegions(ls,lparOsh, IMSSubSysDict ))


    if DiscoverIMSDB and len(IMSSubSysDict) > 0:
        databaseAreaDictionary = {}
        databaseDictionary = {}
        OSHVResult.addAll(getIMSDB(ls, IMSSubSysDict,  databaseAreaDictionary , databaseDictionary))
        OSHVResult.addAll(getAREAs(ls, IMSSubSysDict,  databaseAreaDictionary , databaseDictionary))
        OSHVResult.addAll(processPrograms(ls,IMSSubSysDict, Framework))
    ls.closeClient()

    logger.info ("Finished IMS Discovery")
    return OSHVResult
Example #28
0
    def discover(self, document, appName):
        adapters = []

        # discoverer
        if document:
            logger.debug('Trying to find adapters for %s' % appName)
            xpath = self.getXPath()

            adapterNodeList = xpath.evaluate(r'/application/services/adapter',
                                             document, XPathConstants.NODESET)
            logger.debug('Found %s adapters' % adapterNodeList.getLength())
            if adapterNodeList:
                for adapterNum in xrange(adapterNodeList.getLength()):
                    adapterNode = adapterNodeList.item(adapterNum)
                    # For reconciliation we will use adapter name as application name,
                    # since from app signature we cannot get adapter name only application name and
                    # binding name
                    #adapterName = xpath.evaluate(r'@name', adapterNode, XPathConstants.STRING)
                    adapterName = appName
                    isEnabledStr = xpath.evaluate(r'enabled', adapterNode,
                                                  XPathConstants.STRING)
                    adapter = tibco.Adapter(adapterName,
                                            Boolean.valueOf(isEnabledStr))
                    tibco.each(adapter.addBinding,
                               self._getAdapterBindings(adapterNode))
                    adapters.append(adapter)

        return adapters
Example #29
0
def write_variables(program_name, variable_map, file_path, append=False):
    """
    Write the dictionary of variables to the specified file.
    :param program_name: name of tool that invoked the method which will be written to the variable properties file
    :param variable_map: the dictionary of variables
    :param file_path: the file to which to write the properties
    :param append: defaults to False. Append properties to the end of file
    :raises VariableException if an error occurs while storing the variables in the file
    """
    _method_name = 'write_variables'
    _logger.entering(program_name, file_path, append, class_name=_class_name, method_name=_method_name)
    props = Properties()
    for key in variable_map:
        value = variable_map[key]
        props.setProperty(key, value)

    comment = exception_helper.get_message('WLSDPLY-01731', program_name)
    output_stream = None
    try:
        output_stream = FileOutputStream(File(file_path), Boolean(append))
        props.store(output_stream, comment)
        output_stream.close()
    except IOException, ioe:
        ex = exception_helper.create_variable_exception('WLSDPLY-20007', file_path,
                                                        ioe.getLocalizedMessage(), error=ioe)
        _logger.throwing(ex, class_name=_class_name, method_name=_method_name)
        if output_stream is not None:
            output_stream.close()
        raise ex
Example #30
0
def DiscoveryMain(Framework):

    protocolName = "NTCMD"

    OSHVResult = ObjectStateHolderVector()
    param = Framework.getParameter('discoverSoftware')
    if (param != None) and not Boolean.parseBoolean(param):
        logger.debug(
            'No discovery for software by NTCMD, parameter discoverSoftware is false'
        )
        return OSHVResult

    hostID = Framework.getDestinationAttribute('hostId')

    hostOSH = modeling.createOshByCmdbIdString('host', hostID)

    clientShUtils = None
    try:
        props = Properties()
        props.setProperty(AgentConstants.PROP_NTCMD_AGENT_COMMAND_TIMEOUT,
                          '100000')
        client = Framework.createClient(props)
        if client is None:
            raise Exception, 'Failed to create NTCMD client'
    except Exception, ex:
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, protocolName, Framework)
Example #31
0
def getGlobals(mod):
    mp = HashMap()
    for attrName in mod.__dict__:
        if not attrName.startswith('__'):
            attr = mod.__getattribute__(attrName)
            t = type(attr)
            if t is not list:
                if t is str:
                    mp.put(attrName, attr)
                elif t is int:
                    mp.put(attrName, Integer(attr))
                elif t is float:
                    mp.put(attrName, Float(attr))
                elif t is bool:
                    mp.put(attrName, Boolean(attr))
            else:
                arr = None
                if len(attr) > 0:
                    t = type(attr[0])
                    if t is int:
                        arr = __fillArray(attr, Integer)
                    elif t is float:
                        arr = __fillArray(attr, Float)
                    elif t is str:
                        arr = __fillArray(attr, String)
                mp.put(attrName, arr)
    return mp
Example #32
0
 def setValueAt(self, value, row, col):
     if isinstance(value, bool):
         self.data[row][col] = Boolean(value)
     else:
         self.data[row][col] = value if value else ''
     self.fireTableCellUpdated(row, col)
     return
Example #33
0
def __discoverInstalledSoftware(Framework, OSHVResult, client):
    discoverSoftwareOld = Boolean.parseBoolean(
        Framework.getParameter('discoverInstalledSoftwareByOldMechanism'))

    softNameToInstSoftOSH = {}
    try:
        if discoverSoftwareOld:
            #we close client here since in the software discovery we had to open another client
            #since we changing namespace and reference registry instead of wmi
            logger.debug(
                'The software is discovered using old mechanism. This mechanism is very non-efficient and thus discovery might take time.'
            )
            client.close()
            client = None

            wmi_dis_software_lib.mainFunction(Framework, OSHVResult,
                                              softNameToInstSoftOSH)

            #reopen general WMI client since it will be used in Plug-ins
            logger.debug("Reopening WMI client")
            client = createWmiClient(Framework)
        else:
            wmi_dis_software_lib.mainFunctionWithWbem(Framework, client,
                                                      OSHVResult,
                                                      softNameToInstSoftOSH)
    except:
        errobj = errorobject.createError(
            errorcodes.FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE,
            ['software', 'wmi'], 'Failed to discover software by wmi')
        logger.reportErrorObject(errobj)
        logger.errorException('Failed to discover software by wmi')
    return (softNameToInstSoftOSH, client)
Example #34
0
def DiscoveryMain(Framework):
    fileName = Framework.getParameter('file_name').replace(
        '%PROBE_MGR_RESOURCES_DIR%',
        CollectorsParameters.PROBE_MGR_RESOURCES_DIR)
    string_list_delimiter = Framework.getParameter('string_list_delimiter')
    integer_list_delimiter = Framework.getParameter('integer_list_delimiter')
    relationship_attr_delimiter = Framework.getParameter(
        'relationship_attr_delimiter')
    set_empty_value_flag = Boolean.parseBoolean(
        Framework.getParameter('set_empty_value'))
    if not (fileName and string_list_delimiter and integer_list_delimiter
            and relationship_attr_delimiter):
        logger.reportError('Not all job parameters are set.')
        return
    try:
        workbook = xlsutils.openXlFile(fileName)
        if workbook:
            classModel = ConfigFilesManagerImpl.getInstance(
            ).getCmdbClassModel()
            classModelUtil = xlsutils.ClassModelUtils(classModel,
                                                      integer_list_delimiter,
                                                      string_list_delimiter)
            importer = WorkSheetImporter(workbook,
                                         classModelUtil,
                                         set_empty_value=set_empty_value_flag)
            return importer.processWorkbook()
    except JavaException, ex:
        logger.reportError(ex.getMessage())
        ex.printStackTrace()
        logger.errorException('')
Example #35
0
def disHPUX(host_obj, client, Framework = None, langBund = None, pid2Process = None):
	hostId = Framework.getDestinationAttribute('hostId')
	discoverProcesses = Boolean.parseBoolean(Framework.getParameter('discoverProcesses'))

	myVec = ObjectStateHolderVector()
	
	# Better format, but not supported on all HPUX systems
	#r = client.executeCmd('ps -e -o pid,time,sz,comm,args')
	r = client.execCmd('ps -ef')#V@@CMD_PERMISION tty protocol execution
	if r == None:
		return myVec

	lines = ''
	if(re.search('\r\n',r)):
		lines = r.split('\r\n')
	elif (re.search('\n',r)):
		lines = r.split('\n')
	else:
		return myVec
	processList = []
	pdu = None
	try:
		pdu = processdbutils.ProcessDbUtils(Framework)
		hostOSH = None
		for line in lines:
			## Reg for processes with args
			res = re.search('(\w+)\s+(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)\s(.*)',line)
			if(res):
				cleanArgs = res.group(4)
			else:
				## Reg for processes with no args
				res = re.search('(\w+)\s+(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\-+:/]+)',line)
				if(res):
					cleanArgs = ''
			if(res):
				owner = res.group(1)
				commAndPath = res.group(3)
				pid = res.group(2)
				cleanCommand = ''
				if commAndPath.find('/') == -1:
					cleanCommand = commAndPath
				else:
					res2 = re.search('(.*/)([^/]+)',commAndPath)
					if (res2):
						cleanCommand = res2.group(2)
					else:
						continue
				if hostOSH == None:
					hostOSH = modeling.createOshByCmdbIdString('host', hostId)
				
				commandLine = cleanCommand + ' ' + cleanArgs
				addProcess(pdu, hostId, cleanCommand, pid, commandLine, commAndPath, cleanArgs, processList, discoverProcesses, myVec, hostOSH, None, owner)

		pdu.flushHostProcesses(hostId)
		if pid2Process is not None:
			pid2Process.putAll(pdu.getProcessCmdMap())
	finally:
		if pdu != None:
			pdu.close()
	return myVec
Example #36
0
 def _massage_security_credential(self, result):
     _method_name = 'massage_security_credential'
     # Determine if the SecurityConfiguration/CredentialEncrypted can be removed
     if model_constants.SECURITY_CONFIGURATION_PASSWORD in result:
         # default is false
         if model_constants.SECURITY_CONFIGURATION_CD_ENABLED in result and \
                 Boolean.valueOf(result[model_constants.SECURITY_CONFIGURATION_CD_ENABLED]) == Boolean.TRUE:
             _logger.finer('WLSDPLY-06615',
                           class_name=_class_name,
                           method_name=_method_name)
         else:
             del result[model_constants.SECURITY_CONFIGURATION_PASSWORD]
             _logger.fine('WLSDPLY-06616',
                          class_name=_class_name,
                          method_name=_method_name)
     # Determine if the SecurityConfiguration/NodeManagerEncryptedPassword can be removed
     if model_constants.SECURITY_CONFIGURATION_NM_PASSWORD in result:
         if model_constants.MACHINE in self._dictionary or model_constants.UNIX_MACHINE in self._dictionary:
             _logger.finer('WLSDPLY-06645',
                           class_name=_class_name,
                           method_name=_method_name)
         else:
             del result[model_constants.SECURITY_CONFIGURATION_NM_PASSWORD]
             _logger.finer('WLSDPLY-06646',
                           class_name=_class_name,
                           method_name=_method_name)
Example #37
0
    def test_cast(self):
        from java.lang import Boolean, Object
        b = Boolean(True)
        b_Object = cast(Object, b)
        self.assertIsNot(b, b_Object)
        self.assertEqual(b, b_Object)
        self.assertIs(Boolean.getClass(), b.getClass())
        self.assertIs(Boolean.getClass(), b_Object.getClass())
        self.assertIsNot(Object.getClass(), b_Object.getClass())
        self.assertIs(b_Object, cast(Object, b))
        self.assertIs(b, cast(Boolean, b_Object))

        with self.assertRaisesRegexp(
                TypeError, "cannot create java.lang.Boolean proxy from "
                "java.lang.Object instance"):
            cast(Boolean, Object())
Example #38
0
 def is_lsa_in_attributes(self, lsa_attribute, attribute_list):
     """
     Look for the offline WLST LSA attribute name in one of the MBean's helper lists. The names
     can differ between the LSA attribute and the MBean attribute lists. Attempt to match the LSA
     attribute using different representations of the name.
     :param lsa_attribute: attribute from the offline WLST LSA list
     :param attribute_list: list of attributes from one of the MBean helper maps
     :return: True if the LSA attribute is found in the MBean list
     """
     _method_name = 'is_lsa_in_attributes'
     _logger.entering(lsa_attribute,
                      class_name=self.__class__.__name__,
                      method_name=_method_name)
     found = True
     if lsa_attribute not in attribute_list and not self.__is_found_with_lower_case(
             lsa_attribute, attribute_list):
         if not lsa_attribute.endswith('y') or not \
                self.__is_found_with_lower_case(lsa_attribute[:len(lsa_attribute) - 1] + 'ies', attribute_list):
             if not self.__is_found_with_lower_case(lsa_attribute + 'es',
                                                    attribute_list):
                 if not self.__is_found_with_lower_case(
                         lsa_attribute + 's', attribute_list):
                     found = False
     _logger.exiting(class_name=self.__class__.__name__,
                     method_name=_method_name,
                     result=Boolean(found))
     return found
Example #39
0
 def _check_insert_attribute_model(self, location, model_section, attribute, injector_values):
     _method_name = '_check_insert_attribute_model'
     if attribute not in model_section and (FORCE in injector_values and Boolean(injector_values[FORCE])):
         value = self.__aliases.get_model_attribute_default_value(location, attribute)
         _logger.fine('WLSDPLY-19540', attribute, location.get_folder_path(), value,
                      class_name=_class_name, method_name=_method_name)
         model_section[attribute] = value
 def __composeDown(self):
     
     logger.info("Enter docker compose down")
     try:
         project = getVariableValue("DOCKER_COMPOSE_PROJECT", self.__compName)
         cmdlist=[self.__dockerCompose, "--file", self.__composeFile, "--project-name", project, "down"]
         removeImage = Boolean.parseBoolean(getVariableValue("REMOVE_DOCKER_IMAGE", "false"))
        
         if removeImage:
             cmdlist.extend(["--rmi", "all"])
             
         removeOptions = getVariableValue("DOCKER_REMOVE_OPTIONS")
         if removeOptions and removeOptions.find("--volumes=true") >= 0:
             cmdlist.append("--volumes")
             
         logger.info("Executing:"+ list2str(cmdlist))
         os.environ["DOCKER_HOST"] = "tcp://" + self.__dockerAddr
         os.environ["COMPOSE_HTTP_TIMEOUT"] = "300"
         self.__lock()
         retcode = call(cmdlist)
         logger.info("Return code:" + str(retcode))
     except:
         type, value, traceback = sys.exc_info()
         logger.severe("composeDown error:" + `value`)
         raise
     finally:
         self.__unlock()
             
     logger.info("Exit docker compose down")
Example #41
0
 def is_attribute_in_lsa_map(self, attribute, lsa_attributes):
     """
     Look for the attribute name from one of the MBean helper lists in the offline WLST LSA map.
     Names differ for some attributes between the offline LSA and MBean helper list. Attempt to match
     the attribute in the LSA map using different representations of the name.
     :param attribute: to match in the LSA list
     :param lsa_attributes: list of LSA attributes
     :return: True if the attribute is found in the LSA list
     """
     _method_name = 'is_attribute_in_lsa_map'
     _logger.entering(attribute,
                      class_name=self.__class__.__name__,
                      method_name=_method_name)
     found = True
     if attribute not in lsa_attributes and not self.__is_found_with_lower_case(
             attribute, lsa_attributes):
         if not attribute.endswith('ies') or \
                 not self.__is_found_with_lower_case(attribute[:len(attribute) - 3] + 'y', lsa_attributes):
             if not attribute.endswith('es') or \
                     not self.__is_found_with_lower_case(attribute[:len(attribute) - 2], lsa_attributes):
                 if not attribute.endswith('s') or \
                         not self.__is_found_with_lower_case(attribute[:len(attribute) - 1], lsa_attributes):
                     found = False
     _logger.exiting(class_name=self.__class__.__name__,
                     method_name=_method_name,
                     result=Boolean(found))
     return found
Example #42
0
    def __init__(self, Framework):
        Netlinks_Service.NetlinksService.__init__(self, Framework)
        shouldIgnoreLocal = self.getParameterValue('ignoreLocalConnections')
        if shouldIgnoreLocal == None:
            shouldIgnoreLocal = 'false'
        self.ignoreLocalConnections = Boolean.parseBoolean(shouldIgnoreLocal)
        self.dependencyNameIsKey = modeling.checkIsKeyAttribute(
            'dependency', 'dependency_name')
        self.dependencySourceIsKey = modeling.checkIsKeyAttribute(
            'dependency', 'dependency_source')
        ignoredIpsList = self.getParameterValue('ignoredIps')
        self.ignoredIps = None
        if ignoredIpsList != None:
            ipPatterns = ignoredIpsList.split(',')
            if (len(ipPatterns) > 0) and (ipPatterns[0] != ''):
                for ipPattern in ipPatterns:
                    pattern = String(ipPattern)
                    pattern = String(pattern.replaceAll("\.", "\\\."))
                    pattern = String(pattern.replaceAll("\*", "\\\d+"))
                    try:
                        m = Pattern.compile(pattern)
                        if self.ignoredIps == None:
                            self.ignoredIps = ArrayList()
                        self.ignoredIps.add(m)
                    except:
                        logger.debug('Failed to compile ip pattern:',
                                     ipPattern)

        self.initializeServices()
Example #43
0
    def __init__(self, Framework):
        Netlinks_Service.NetlinksService.__init__(self, Framework)
        shouldIgnoreLocal = self.getParameterValue('ignoreLocalConnections')
        if shouldIgnoreLocal == None:
            shouldIgnoreLocal = 'false'
        self.ignoreLocalConnections = Boolean.parseBoolean(shouldIgnoreLocal)
        self.dependencyNameIsKey = modeling.checkIsKeyAttribute('dependency', 'dependency_name')
        self.dependencySourceIsKey = modeling.checkIsKeyAttribute('dependency', 'dependency_source')
        ignoredIpsList = self.getParameterValue('ignoredIps')
        self.ignoredIps = None
        if ignoredIpsList != None:
            ipPatterns = ignoredIpsList.split(',')
            if (len(ipPatterns) > 0) and (ipPatterns[0] != ''):
                for ipPattern in ipPatterns:
                    pattern = String(ipPattern)
                    pattern = String(pattern.replaceAll("\.", "\\\."))
                    pattern = String(pattern.replaceAll("\*", "\\\d+"))
                    try:
                        m = Pattern.compile(pattern)
                        if self.ignoredIps == None:
                            self.ignoredIps = ArrayList()
                        self.ignoredIps.add(m)
                    except:
                        logger.debug('Failed to compile ip pattern:', ipPattern)


        self.initializeServices()
Example #44
0
 def getPayloadContent(self):
     mimeType = self.__mimeType
     print " * single.py: payload content mimeType=%s" % mimeType
     contentStr = ""
     if mimeType.startswith("text/"):
         if mimeType == "text/html":
             contentStr = '<iframe class="iframe-preview" src="%s/%s/download/%s"></iframe>' % (
                 contextPath,
                 portalId,
                 self.__oid,
             )
         else:
             pid = self.__oid[self.__oid.rfind("/") + 1 :]
             payload = self.__storage.getPayload(self.__oid, pid)
             print " * single.py: pid=%s payload=%s" % (pid, payload)
             if payload is not None:
                 sw = StringWriter()
                 sw.write("<pre>")
                 IOUtils.copy(payload.getInputStream(), sw)
                 sw.write("</pre>")
                 sw.flush()
                 contentStr = sw.toString()
     elif (
         mimeType == "application/pdf"
         or mimeType.find("vnd.ms") > -1
         or mimeType.find("vnd.oasis.opendocument.") > -1
     ):
         # get the html version if exist...
         pid = os.path.splitext(self.__pid)[0] + ".htm"
         print " * single.py: pid=%s" % pid
         # contentStr = '<iframe class="iframe-preview" src="%s/%s/download/%s/%s"></iframe>' % \
         #    (contextPath, portalId, self.__oid, pid)
         payload = self.__storage.getPayload(self.__oid, pid)
         saxReader = SAXReader(Boolean.parseBoolean("false"))
         try:
             document = saxReader.read(payload.getInputStream())
             slideNode = document.selectSingleNode("//*[local-name()='body']")
             # linkNodes = slideNode.selectNodes("//img")
             # contentStr = slideNode.asXML();
             # encode character entities correctly
             slideNode.setName("div")
             out = ByteArrayOutputStream()
             format = OutputFormat.createPrettyPrint()
             format.setSuppressDeclaration(True)
             format.setExpandEmptyElements(True)
             writer = XMLWriter(out, format)
             writer.write(slideNode)
             writer.close()
             contentStr = out.toString("UTF-8")
         except:
             traceback.print_exc()
             contentStr = '<p class="error">No preview available</p>'
     elif mimeType.startswith("image/"):
         src = "%s/%s" % (self.__oid, self.__pid)
         contentStr = (
             '<a class="image" href="%(src)s"  style="max-width:98%%">'
             '<img src="%(src)s" style="max-width:100%%" /></a>' % {"src": self.__pid}
         )
     return contentStr
Example #45
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    client = None
    layer2_connections_cdp = None
    layer2_connections_lldp = None
    try:
        try:
            client = Framework.createClient()
        except:
            errMsg ='Exception while creating %s client: %s' % (ClientsConsts.SNMP_PROTOCOL_NAME, sys.exc_info()[1])
            errormessages.resolveAndReport(str(sys.exc_info()[1]), ClientsConsts.SNMP_PROTOCOL_NAME, Framework)
            logger.debugException(errMsg)
        else:
            host_id = Framework.getDestinationAttribute('hostId')
            discover_cdp_mib = Boolean.parseBoolean(Framework.getParameter('discoverCdpMib'))
            discover_lldp_mib = Boolean.parseBoolean(Framework.getParameter('discoverLldpMib'))
            local_device_discoverer = LocalDeviceDiscoverer(client, host_id)
            local_devices = local_device_discoverer.get_local_devices()
            if not local_devices or len(local_devices) == 0:
                logger.reportError('Failed to get local device info')

            if discover_cdp_mib:
                cdp_discoverer = CdpDiscoverer(client)
                remote_devices_cdp = cdp_discoverer.get_remote_devices()
                if remote_devices_cdp:
                    layer2_connections_cdp = get_layer2_connections(local_devices, remote_devices_cdp)
                    for layer2_connection in layer2_connections_cdp:
                        OSHVResult.addAll(build_layer2_connection(layer2_connection))

            if discover_lldp_mib:
                lldp_discoverer = LldpDiscoverer(client)
                remote_devices_lldp = lldp_discoverer.get_remote_devices()
                if remote_devices_lldp:
                    layer2_connections_lldp = get_layer2_connections(local_devices, remote_devices_lldp)
                    for layer2_connection in layer2_connections_lldp:
                        OSHVResult.addAll(build_layer2_connection(layer2_connection))

            if (not layer2_connections_cdp or len(layer2_connections_cdp) == 0) and (not layer2_connections_lldp or len(layer2_connections_lldp) == 0):
                logger.reportError('No data collected')

    finally:
        if client != None:
            client.close()
    return OSHVResult
Example #46
0
def disWinOS(host_obj, shell, Framework, langBund = None, pid2Process = None):
	discoverProcesses = Boolean.parseBoolean(Framework.getParameter('discoverProcesses'))
	OSHVResult = None
	if discoverProcesses:
		OSHVResult = ObjectStateHolderVector()
	
	if not NTCMD_HR_Dis_Process_Lib.discoverProcessesByWmic(shell, OSHVResult, host_obj, Framework, pid2Process):
		NTCMD_HR_Dis_Process_Lib.discoverProcesses(shell, OSHVResult, host_obj, Framework, pid2Process)
	return OSHVResult
Example #47
0
 def bool_params(self, **kwargs):
     for name, default_value in kwargs.iteritems():
         value = self.__framework.getParameter(name)
         if value is not None:
             value = Boolean.parseBoolean(value)
         else:
             value = default_value
         self.__obj[name] = value
     return self
def _obtainParams(framework):
    zoneNameList = framework.getParameter("zoneList")
    splitRegexp = re.compile('[,;]')

    isNonEmptyString = lambda s: s and s.strip()
    zoneNameList = filter(isNonEmptyString,
                          map(string.strip, splitRegexp.split(zoneNameList)))

    from java.lang import Boolean
    includeOutscopeIPs = framework.getParameter('includeOutscopeIPs')
    includeOutscopeIPs = Boolean.valueOf(includeOutscopeIPs)

    reportBrokenAliases = framework.getParameter('reportBrokenAliases')
    reportBrokenAliases = Boolean.valueOf(reportBrokenAliases)

    ip = framework.getDestinationAttribute('ip_address')

    return zoneNameList, includeOutscopeIPs, ip, reportBrokenAliases
def _get_enqueue_replicated_flag(shell, pf_path):
    r'@types: shellutils.Shell, str -> bool?'
    output = _grep(shell, 'enque/server/replication', pf_path)
    if output:
        ENQUE_REPLICATION_RE = "enque/server/replication\s*=\s*(true|false)"
        m_obj = re.search(ENQUE_REPLICATION_RE, output.lower())
        if m_obj:
            is_replicated = Boolean.valueOf(m_obj.group(1))
            return is_replicated
Example #50
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    logger.debug('Start nmap_osfingerprint.py')
    ip = Framework.getDestinationAttribute('ip_address')
    timeout = Framework.getParameter('nmap_host_timeout')
    if not str(timeout).isdigit():
        msg = "Timeout parameter value must be a digit"
        logger.debug(msg)
        errormessages.resolveAndReport(msg, ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME, Framework)
        return OSHVResult

    timeout = int(timeout) * 1000
    scanKnownPortsOnly = Boolean.parseBoolean(Framework.getParameter('scan_known_ports_only'))
    portstoscan	= Framework.getParameter('scan_these_ports_only')
    doServiceFingerprints =Boolean.parseBoolean(Framework.getParameter('Perform_Port_Fingerprints'))
    createApp = Boolean.parseBoolean(Framework.getParameter('Create_Application_CI'))
    discoverOsName =Boolean.parseBoolean(Framework.getParameter('discover_os_name'))
    nmapLocation = Framework.getParameter('nmap_location')
    #discover_UDP_Ports	= int(Framework.getParameter('Discover_UDP_Ports'))
    discoverUdpPorts = 0

    agent_root_dir=CollectorsParameters.BASE_PROBE_MGR_DIR
    agent_ext_dir = agent_root_dir + CollectorsParameters.getDiscoveryResourceFolder() + CollectorsParameters.FILE_SEPARATOR
    tmp_file_name = agent_ext_dir + string.replace(ip,'.','_') + time.strftime("%H%M%S",time.gmtime(time.time())) + 'nmap.xml'

    syncNmapPortConfigFile(agent_root_dir)

    logger.debug('temp file for storing nmap results: ', tmp_file_name)
    try:
        client = Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
        try:
            performNmapDiscover(client, ip, tmp_file_name,timeout,agent_ext_dir,scanKnownPortsOnly,portstoscan,doServiceFingerprints, discoverUdpPorts, nmapLocation)
            if os.path.exists(tmp_file_name):
                logger.debug('start processing the nmap results')
                processNmapResult(tmp_file_name, OSHVResult, discoverOsName, doServiceFingerprints, createApp, Framework)
            else:
                raise ValueError, 'Error nmap result file is missing: %s' % tmp_file_name
        finally:
            client.close()
            File(tmp_file_name).delete()
    except Exception, e:
        msg = str(e.getMessage())
        logger.debug(msg)
        errormessages.resolveAndReport(msg, ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME, Framework)
Example #51
0
 def getPayloadContent(self):
     mimeType = self.__mimeType
     print " * detail.py: payload content mimeType=%s" % mimeType
     contentStr = ""
     if mimeType == "application/octet-stream":
         dcFormat = self.__json.get("response/docs/dc_format")
         if dcFormat is not None:
             dcFormat = dcFormat[1:-1]
         print dcFormat, mimeType
         if dcFormat != mimeType:
             return "<div><em>(File not found)</em></div>"
         else:
             return "<div><em>(Binary file)</em></div>"
     elif mimeType.startswith("text/"):
         if mimeType == "text/html":
             contentStr = '<iframe class="iframe-preview" src="%s/%s/download/%s"></iframe>' % \
                 (contextPath, portalId, self.__oid)
         else:
             pid = self.__oid[self.__oid.rfind("/")+1:]
             payload = self.__storage.getPayload(self.__oid, pid)
             #print " * detail.py: pid=%s payload=%s" % (pid, payload)
             if payload is not None:
                 sw = StringWriter()
                 sw.write("<pre>")
                 IOUtils.copy(payload.getInputStream(), sw)
                 sw.write("</pre>")
                 sw.flush()
                 contentStr = sw.toString()
     elif mimeType == "application/pdf" or mimeType.find("vnd.ms")>-1 or mimeType.find("vnd.oasis.opendocument.")>-1:
         # get the html version if exist...
         pid = os.path.splitext(self.__pid)[0] + ".htm"
         print " * detail.py: pid=%s" % pid
         #contentStr = '<iframe class="iframe-preview" src="%s/%s/download/%s/%s"></iframe>' % \
         #    (contextPath, portalId, self.__oid, pid)
         payload = self.__storage.getPayload(self.__oid, pid)
         saxReader = SAXReader(Boolean.parseBoolean("false"))
         try:
             document = saxReader.read(payload.getInputStream())
             slideNode = document.selectSingleNode("//*[local-name()='body']")
             #linkNodes = slideNode.selectNodes("//img")
             #contentStr = slideNode.asXML();
             # encode character entities correctly
             slideNode.setName("div")
             out = ByteArrayOutputStream()
             format = OutputFormat.createPrettyPrint()
             format.setSuppressDeclaration(True)
             format.setExpandEmptyElements(True)
             writer = XMLWriter(out, format)
             writer.write(slideNode)
             writer.close()
             contentStr = out.toString("UTF-8")
         except:
             traceback.print_exc()
             contentStr = "<p class=\"error\">No preview available</p>"
     return contentStr
 def getUsers(self, domainName):
     ''' Get users for specified domain name.
     Information about users contains name, description, UID, full name, lock status,
     disabled or enabled status.
     str -> list(User)
     @command: SELECT Description, Disabled, Domain, FullName, Lockout, Name, SID FROM Win32_UserAccount  WHERE Domain = '<domainName>'
     @raise Exception: if WMI query failed
     '''
     users = []
     builder = self._provider.getBuilder('Win32_UserAccount').addWmiObjectProperties('Name','FullName','Description','SID','Disabled','Domain','Lockout')
     builder.addWhereClause("Domain = '%s'" % domainName)
     accounts = self._provider.getAgent().getWmiData(builder, timeout = 180000)
     for account in accounts:
         user = User(account.Name, description = account.Description, uid = account.SID)
         user.fullName = account.FullName
         user.isDisabled = Boolean.valueOf(account.Disabled)
         user.domain = account.Domain
         user.isLocked = Boolean.valueOf(account.Lockout)
         users.append(user)
     return users
Example #53
0
 def __init__(self, Framework):
     self.Framework = Framework
     self.conn = self.Framework.getProbeDatabaseConnection(ProcessToProcess.CONTEXT)
     self.knownPortsConfigFile = self.Framework.getConfigFile(CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME)
     self.shouldIgnoreLocal = Boolean.parseBoolean(self.Framework.getParameter('ignoreP2PLocalConnections'))
     self.knownListeningPorts = self.getKnownListeningPortsSet()
     self.requestedServices = self.getRequestedPortsSet()
     self.hostID = Framework.getDestinationAttribute('hostId')
     self.ignoredProcesses = HashSet()
     self.processMap = {}
     self.getProcessesToFilter()
 def cleanup(self):
     "cleanup"
     
     logger.info("Enter cleanup")
     try:
         copyContainerEnvironment()
         removeContainer = Boolean.parseBoolean(getVariableValue("REMOVE_DOCKER_CONTAINER", "true"))
         removeImage = Boolean.parseBoolean(getVariableValue("REMOVE_DOCKER_IMAGE", "false"))
         
         for index in range(len(self.__dockerContainerName) - 1, -1, -1):
             if removeContainer:
                 self.__rm(index)
         
             if removeImage:
                 self.__rmi(index)
     except:
         type, value, traceback = sys.exc_info()
         logger.warning("cleanup error:" + `value`)
         
     logger.info("Exit cleanup")
def getArchiveDeployProperty(name, properties, default, parse=False):
    value = default
    
    try:
        if properties:
            value = properties.getProperty(name)
            if value and parse:
                value = Boolean.parseBoolean(value)
    except:
        pass
    
    return value
Example #56
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    CmdbOIDFactory = CmdbObjectID.Factory
    hostId = CmdbOIDFactory.restoreObjectID(Framework.getDestinationAttribute('hostId'))
    sqlServerId = CmdbOIDFactory.restoreObjectID(Framework.getDestinationAttribute('id'))

    try:
        props = Properties()
 
        instance_name = Framework.getDestinationAttribute('instanceName')
        if instance_name and instance_name != 'NA' and instance_name.find('\\') != -1:
            props.setProperty('sqlprotocol_dbsid', instance_name[instance_name.find('\\')+1:])
        mssqlClient = Framework.createClient(props)
        connection = SqlServerConnection.ClientSqlServerConnection(mssqlClient)
        logger.debug("got connection")
        discoveryOptions = SqlServerDiscoveryOptions()
        discoveryOptions.discoverConfigs = Boolean.parseBoolean(Framework.getParameter('discoverConfigs'))
        discoveryOptions.discoverDbUser = Boolean.parseBoolean(Framework.getParameter('discoverDbUser'))
        discoveryOptions.discoverSqlFile = Boolean.parseBoolean(Framework.getParameter('discoverSqlFile'))
        discoveryOptions.discoverSqlJob = Boolean.parseBoolean(Framework.getParameter('discoverSqlJob'))
        discoveryOptions.discoverProcedures = Boolean.parseBoolean(Framework.getParameter('discoverStoredProcedures'))
        discoveryOptions.discoverInternalProcedures = Boolean.parseBoolean(Framework.getParameter('discoverInternalProcedures'))

        sqlServer = SqlServer.SqlServer(connection, discoveryOptions)
        OSHVResult.addAll(sqlServer.collectData(hostId, sqlServerId, discoveryOptions.discoverConfigs))
        mssqlClient.close()
    except JavaException, ex:
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, ClientsConsts.SQL_PROTOCOL_NAME, Framework)
Example #57
0
def updateWithPrePostScriptCmd(Framework, commandLine):
    isPrePostScriptAllowed = Boolean.parseBoolean(Framework.getParameter('IsPrePostScriptAllowed'))
    prePostScriptExecTimeout = Integer.parseInt(Framework.getParameter('PrePostScriptExecTimeout'))
    logger.debug("isPrePostScriptAllowed:", isPrePostScriptAllowed)
    if  isPrePostScriptAllowed:
        deltaParams = ' -scripts:. '
        scriptTimeoutParam = ''
        if prePostScriptExecTimeout > 0:
            scriptTimeoutParam = ' -scriptstimeout:' + str(prePostScriptExecTimeout) + ' '
        index = String(commandLine).indexOf(ENTERPRISE_MODE) + String(ENTERPRISE_MODE).length()
        commandLine = commandLine[0:index] + deltaParams + scriptTimeoutParam + commandLine[index + 1:]
        logger.debug('After apply pre/post scripts, scanner execution command updated to ', commandLine)
    return commandLine
Example #58
0
 def __init__(self):
     self.__portal = Services.portalManager.get(portalId)
     sessionNav = self.__portal.get("portal/use-session-navigation", "true")
     self.__useSessionNavigation = Boolean.parseBoolean(sessionNav)
     self.__result = JsonConfigHelper()
     if self.__useSessionNavigation:
         self.__pageNum = sessionState.get("pageNum", 1)
     else:
         self.__pageNum = 1
     self.__selected = ArrayList()
     self.__fqParts = []
     self.__searchField = formData.get("searchField", "full_text")
     self.__search()