Beispiel #1
0
def load_zones(app):
    """Read favourite zones
    """
    app.zones = []
    favZonesDir = File(File.separator.join([app.SCRIPTDIR,
                                            "configuration",
                                            "favourite_zones"]))
    for zoneFile in sorted(favZonesDir.listFiles()):
        name = zoneFile.getName()[:-4]
        fileName = zoneFile.getPath()
        zoneFile = open(fileName)
        fileContent = zoneFile.read()
        if len(fileContent.split("|")) == 2:
            geomString, country = fileContent.split("|")
            country = country.upper()
        else:
            geomString = fileContent
            country = ""
        zoneFile.close()
        zType = "rectangle"
        try:
            Integer.parseInt(geomString[0])
        except NumberFormatException:
            zType = "polygon"
        zone = Zone(app, name, zType, geomString, country)
        app.zones.append(zone)
        if name == app.favZoneName:
            app.favZone = zone

    #Fav zone is active but its data is missing
    if app.favouriteZoneStatus and app.favZone is None:
        app.favouriteZoneStatus = False
def retrieve_an_archive(cust_id, archive_name, user_id, chunk_hint, file_name, output_ids):
    print "\nretrieve_a_chunk routine:: output file_name is :", file_name

    try:
        outfile_stream = FileOutputStream(file_name)
    except:
        print "retrieve_a_chunk routine:: Failed to open output stream on file : ", file_name, "..returning"
        return None

    # retrieve data
    mc = ManagementContainer.getInstance()
    rm = mc.getRecoveryManager()

    l_cust_id = Integer.parseInt(cust_id);
    l_user_id = Integer.parseInt(user_id);
    sosw = IRecoveryManager.SimpleOutputStreamWrapper(outfile_stream)

    try:
        rm.createPerUserActiveRecoveryArchiveFile(l_cust_id, archive_name, l_user_id, sosw, chunk_hint)
    except:
        print "retrieve_a_chunk routine:: `Exception while creating active recovery archive..returning"
        sys.exc_info()[1].printStackTrace()

        print("*** print_exc:")
        traceback.print_exc(file=sys.stdout)
        outfile_stream.close()
        raise

    outfile_stream.close()
    return get_chunk_hint(file_name, output_ids)
Beispiel #3
0
 def test_number_format(self):
     try:
         Integer.parseInt('asdf')
     except Exception as ex:
         if jep.USE_MAPPED_EXCEPTIONS:
             self.assertTrue(isinstance(ex, jep.NumberFormatException))
         else:
             self.assertEquals(ex.java_name, 'java.lang.NumberFormatException')
 def warn(self, e):
     errorNumber = self.textfield.getText()
     if errorNumber == "":
         self.textfield.setBorder(self.defaultborder)
         return
     try:
         Integer.parseInt(errorNumber)
     except NumberFormatException:
         self.textfield.setBorder(BorderFactory.createLineBorder(Color.RED, 1))
         return
     self.textfield.setBorder(BorderFactory.createLineBorder(Color.GREEN, 1))
    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'))
Beispiel #6
0
    def servicesPorts(self, onlyKnownPorts = 1):
        services = self.Framework.getParameter('services')
        if logger.isDebugEnabled():
            logger.debug('Requested services:', services)
        if (services == None) or (len(services) == 0) or (services == '*'):
            if onlyKnownPorts:
                portsInfo = self.knownPortsConfigFile.getTcpPorts()
                services = ''
                delimiter = ''
                for info in portsInfo:
                    services = services + delimiter + str(info.getPortNumber())
                    delimiter = ','
                if len(services) == 0:
                    return services
            else:
                return ''

        names = services.split(',')
        ports = ''
        delimiter = ''
        for name in names:
            portNums = self.knownPortsConfigFile.getPortByName(name)
            if (portNums == None) or (len(portNums) == 0):
                try:
                    portNums = [Integer.parseInt(name)]
                except:
                    logger.debug('Failed to resolve service port number:', name)
                    continue
            for portNum in portNums:
                ports = ports + delimiter + str(portNum)
                delimiter = ','
        if logger.isDebugEnabled():
            logger.debug('Requested services ports:', ports)
        return ports
 def convertToIp(self, encodedIp):
     #TODO: Make it Python
     ipParts = []
     for i in range(4):
         ipParts.append(encodedIp[:2])
         encodedIp = encodedIp[2:]
     ip = ''
     for ipPart in ipParts:
         ip += str(Integer.parseInt(ipPart, 16)) + '.'
     ip = ip[:len(ip)-1]
     return ip
Beispiel #8
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
def parseMappingString(mappingString):
    bitPositions = TreeSet()
    bytesNumber = len(mappingString) / SYMBOLS_PER_BYTE

    for i in range(bytesNumber):
        currentPosition = i * SYMBOLS_PER_BYTE
        currentByteString = mappingString[currentPosition : currentPosition + SYMBOLS_PER_BYTE]

        currentByte = Integer.parseInt(currentByteString, 16)

        for j in range(BITS_IN_SYMBOL):
            if (currentByte & 1) == 1:
                bitPositions.add(i * BITS_IN_SYMBOL + BITS_IN_SYMBOL - j)
            currentByte = currentByte >> 1

    return list(ArrayList(bitPositions))
Beispiel #10
0
    def read_gui(self):
        """Read preferences from gui
        """
        username = self.userTextField.getText()
        level = self.levelsCombo.getSelectedItem()
        limit = self.limitTextField.getText()
        try:
            limit = Integer.parseInt(limit)
            if limit > 500:
                limit = 500
            limit = str(limit)
        except NumberFormatException:
            limit = ""

        preferences = {"username": username.strip(),
                       "level": level,
                       "limit": limit}
        return preferences
    def getRequestedPortsSet(self):
        services = self.Framework.getParameter('P2PServerPorts')
        if logger.isDebugEnabled():
            logger.debug('Requested services:', services)
        if (services == None) or (len(services) == 0) or (services == '*'):
            return None

        names = services.split(',')
        portsSet = HashSet()
        for name in names:
            portNums = self.knownPortsConfigFile.getPortByName(name)
            if portNums == None:
                try:
                    portNums = [Integer.parseInt(name)]
                except:
                    logger.debug('Failed to resolve service port number:', name)
                    continue
            for portNum in portNums:
                portsSet.add(portNum)
        return portsSet
    def getKnownListeningPortsSet(self):
        ports = self.Framework.getParameter('knownListeningPorts')
        portsSet = HashSet()
        if logger.isDebugEnabled():
            logger.debug('Known Listening Ports:', ports)
        if (ports == None) or (len(ports) == 0):
            return None
        if (ports == '*'):
            portsSet.add('*')
            return portsSet

        names = ports.split(',')
        for name in names:
            portNums = self.knownPortsConfigFile.getPortByName(name)
            if portNums == None:
                try:
                    portNums = [Integer.parseInt(name)]
                except:
                    logger.debug('Failed to resolve service port number:', name)
                    continue
            for portNum in portNums:
                portsSet.add(portNum)
        return portsSet
from java.net import InetSocketAddress
from java.lang import String
from java.util.concurrent import TimeUnit, Future
from java.util import ArrayList
from java.lang import System, Integer

log = grinder.logger.info

random = Random()

# Warm up parameters
warmUpOpCount = 1000
warmUpSizeValue = 1

# Test parameters
opCount = Integer.parseInt(System.getProperty("grinder.numOpsPerThread", "10000"))
writePercentage = 20
numberOfKeys = 1000
pooledKeys = ArrayList()
sizeOfValue = 1000

test1 = Test(1, "Warmup (%i ops)" % warmUpOpCount)
test2 = Test(2, "Read (%i ops per thread)" % opCount)
test3 = Test(3, "Put (%i ops per thread)" % opCount)

class TestRunner:

   def __init__(self):
      self.doInit()
      log("Warm up operation count is %i" % warmUpOpCount)
      log("Test operation count is %i" % opCount)
Beispiel #14
0
 def indirect_parse(self, s):
     return Integer.parseInt(s)
Beispiel #15
0
 def get_port(self):
     return Integer.parseInt(
             self.get("rabbitmq", "port")
             )
Beispiel #16
0
 def test_number_format(self):
     try:
         Integer.parseInt('asdf')
     except Exception as ex:            
         self.assertIn('java.lang.NumberFormatException', str(ex.message))
Beispiel #17
0
 def run():
     from java.lang import Integer
     Integer.parseInt(
         "Expected Java exception (this is not a test failure)")
    def logButtonActionPerformed(
            self, evt):  #GEN-FIRST:event_logButtonActionPerformed
        stdout = PrintWriter(self.callbacks.getStdout(), True)
        stderr = PrintWriter(self.callbacks.getStderr(), True)

        try:
            #Connect to the database and create the collections
            mongo = MongoClient(self.mongohost.getText(),
                                Integer.parseInt(self.mongoport.getText()))
            db = mongo.getDB("sitelogger")
            siteUrl = URL(self.website.getText())
            tableSite = db.getCollection(
                siteUrl.getHost().replace("\\.", "_") + "_site")
            tableVuln = db.getCollection(
                siteUrl.getHost().replace("\\.", "_") + "_vuln")

            #Retrieve SiteMap HTTP Requests and Responses and save to the database
            allReqRes = self.callbacks.getSiteMap(self.website.getText())
            for rc in xrange(0, len(allReqRes)):
                document = BasicDBObject()
                document.put("host", allReqRes[rc].getHost())
                document.put("port", allReqRes[rc].getPort())
                document.put("protocol", allReqRes[rc].getProtocol())
                document.put("URL", allReqRes[rc].getUrl().toString())
                document.put("status_code", allReqRes[rc].getStatusCode())
                if (allReqRes[rc].getRequest() != None):
                    document.put(
                        "request",
                        self.helpers.base64Encode(allReqRes[rc].getRequest()))

                if (allReqRes[rc].getResponse() != None):
                    document.put(
                        "response",
                        self.helpers.base64Encode(allReqRes[rc].getResponse()))

                tableSite.insert(document)

            #Retrieve Scan findings and save to the database
            allVulns = self.callbacks.getScanIssues(self.website.getText())
            for vc in xrange(0, len(allVulns)):
                document = BasicDBObject()
                document.put("type", allVulns[vc].getIssueType())
                document.put("name", allVulns[vc].getIssueName())
                document.put("detail", allVulns[vc].getIssueDetail())
                document.put("severity", allVulns[vc].getSeverity())
                document.put("confidence", allVulns[vc].getConfidence())
                document.put("host", allVulns[vc].getHost())
                document.put("port", allVulns[vc].getPort())
                document.put("protocol", allVulns[vc].getProtocol())
                document.put("URL", allVulns[vc].getUrl().toString())
                if (len(allVulns[vc].getHttpMessages()) > 1):
                    if (allVulns[vc].getHttpMessages()[0].getRequest() !=
                            None):
                        document.put(
                            "request",
                            self.helpers.base64Encode(
                                allVulns[vc].getHttpMessages()
                                [0].getRequest()))

                    if (allVulns[vc].getHttpMessages()[0].getResponse() !=
                            None):
                        document.put(
                            "response",
                            self.helpers.base64Encode(
                                allVulns[vc].getHttpMessages()
                                [0].getResponse()))

                tableVuln.insert(document)

            self.callbacks.issueAlert("Data Saved!")

        except UnknownHostException as ex:
            stderr.println("Mongo DB Connection Error:" + ex.toString())
        except MalformedURLException as ex:
            stderr.println("Malformed URL:" + ex.toString())
Beispiel #19
0
def parameterScan():
	global scan_device_server_name	
	global scan_1d_front
	global scan_2d_front
	global path 
	global data_file 
	global file_extension 
	global actuators
	global sensors 
	global n_steps 
	global integration_time 
	global start_position_actuators_1D 
	global end_position_actuators_1D 
	global n_steps2 
	global start_position_actuators_2D 
	global end_position_actuators_2D 
	global timebase 
	global scan_number 
	global scan_type 
	global has_trajectory	
	global file_path
	global actuators2D
	#open the file in read only mode
	#file = DataInputStream(FileInputStream("D:\eclipse\workspace\passerelle-soleil\sample-models\paramscan.txt"))
	file =  open(file_path,'r')
	parameters = {}
	for line in file.readlines():
		#print "line ",line
		tokens = line.split('=')
		#print "tokens ",tokens
		if(len(tokens) == 2):
			tok0 = String(tokens[0])
			tok1 = String(tokens[1])
			tok0 = tok0.trim()
			tok1 = tok1.trim()
			parameters[tok0] = tok1
			print tok0,":",tok1
	
	if(parameters.has_key("scan_device_server_name")):
		scan_device_server_name = parameters["scan_device_server_name"]
		
	if(parameters.has_key("scan_1d_front")):
		scan_1d_front = parameters["scan_1d_front"]
		
	if(parameters.has_key("scan_2d_front")):
		scan_2d_front = parameters["scan_2d_front"]
	
	if(parameters.has_key("path")):
		path = parameters["path"]
	
	if(parameters.has_key("data_file")):
		data_file = parameters["data_file"]
	
	if(parameters.has_key("file_extension")):
		file_extension = parameters["file_extension"]
	
	if(parameters.has_key("actuators")):
		actuators = parameters["actuators"].split(",")
		#print  "parameterScan actuators ",parameters["actuators"].split(",")
   	
   	if(parameters.has_key("sensors")):
		sensors = parameters["sensors"].split(",")
  	
  	#if(parameters.has_key("n_steps")):
		#n_steps = Integer.parseInt(parameters["n_steps"])
   	
   	#if(parameters.has_key("integration_time")):
		#integration_time = Double.parseDouble(parameters["integration_time"])
	
	#if(parameters.has_key("start_position_actuators_1D")):	
	#	stringTable = parameters["start_position_actuators_1D"].split(",")
	#	start_position_actuators_1D = []
	#	for i in stringTable:
	#		start_position_actuators_1D.append(Double.parseDouble(i))
   	
   	if(parameters.has_key("end_position_actuators_1D")):
		stringTable = parameters["end_position_actuators_1D"].split(",")
		end_position_actuators_1D = []
		for i in stringTable:
			end_position_actuators_1D.append(Double.parseDouble(i))
	
	if(parameters.has_key("actuators2D")):
		actuators2D = parameters["actuators2D"].split(",")
		#print  "parameterScan actuators ",parameters["actuators"].split(",")
	
	if(parameters.has_key("n_steps2")):
		n_steps2 = Integer.parseInt(parameters["n_steps2"])
	
	if(parameters.has_key("start_position_actuators_2D")):	
		stringTable = parameters["start_position_actuators_2D"].split(",")
		start_position_actuators_2D = []
		for i in stringTable:
			start_position_actuators_2D.append(Double.parseDouble(i))
   	
   	if(parameters.has_key("end_position_actuators_2D")):
		stringTable = parameters["end_position_actuators_2D"].split(",")
		end_position_actuators_2D = []
		for i in stringTable:
			end_position_actuators_2D.append(Double.parseDouble(i))
   	
   	if(parameters.has_key("timebase")):
		timebase = parameters["timebase"]
	
	if(parameters.has_key("scan_number")):
		scan_number = Integer.parseInt(parameters["scan_number"])
   	
   	if(parameters.has_key("scan_type")):
		scan_type = Integer.parseInt(parameters["scan_type"])
   	
   	if(parameters.has_key("has_trajectory")):
		has_trajectory = Integer.parseInt(parameters["has_trajectory"])
Beispiel #20
0
    def on_saveBtn_clicked(self, event):
        """Read preferences from gui and save them to config.properties
           file
        """
        #print "\n- saving preferences to config file"
        onOff = {True: "on", False: "off"}

        #1 Tab
        #check for update
        self.app.properties.setProperty("check_for_update",
                                        onOff[self.updateCBtn.isSelected()])
        #tools status
        for toolIndex, tool in enumerate(self.app.realTools):
            prop = "tool.%s" % tool.name
            toolCBtn = self.toolsCBtns[toolIndex]
            self.app.properties.setProperty(prop,
                                            onOff[toolCBtn.isSelected()])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            if button.isSelected():
                self.app.properties.setProperty("layers_mode", mode)
                break

        #max errors number
        try:
            num = Integer.parseInt(self.maxErrorsNumberTextField.getText())
        except NumberFormatException:
            num = ""
        self.app.properties.setProperty("max_errors_number", str(num))

        #2 Tab
        #Favourite zones
        changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones],
                   "deleted": [z for z in self.app.zones if not z in self.app.tempZones]}
        #delete files of removed favourite zones
        for zone in changes["deleted"]:
            f = File(File.separator.join([self.app.SCRIPTDIR,
                                          "configuration",
                                          "favourite_zones",
                                          "%s.txt" % zone.name]))
            f.delete()
        #create files for new favourite zones
        for zone in changes["new"]:
            print "\nsave new zone", zone.name
            fileName = File.separator.join([self.app.SCRIPTDIR,
                                            "configuration",
                                            "favourite_zones",
                                            "%s.txt" % zone.name])
            f = open(fileName, "w")
            zoneData = zone.geomString
            if zone.country != "":
                zoneData += "|" + zone.country
            f.write(zoneData.encode("utf-8"))
            f.close()

        self.app.zones = self.app.tempZones
        if len(self.app.zones) == 0:
            self.app.favZone = None
            self.app.properties.setProperty("favourite_area.name",
                                            "")
            self.favZoneStatusCBtn.setSelected(False)
        else:
            if len(self.zonesTable.getSelectedRows()) == 0:
                self.app.favZone = self.app.zones[0]
            else:
                self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]]
            self.app.properties.setProperty("favourite_area.name",
                                            self.app.favZone.name)
        favZoneStatus = self.favZoneStatusCBtn.isSelected()
        self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus])
        self.app.favouriteZoneStatus = favZoneStatus

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                for pref, value in tool.prefsGui.read_gui().iteritems():
                    prefKey = "tool.%s.%s" % (tool.name, pref)
                    self.app.properties.setProperty(prefKey, value)

        self.app.save_config()
        self.dispose()
Beispiel #21
0
 def test_number_format(self):
     try:
         Integer.parseInt('asdf')
     except Exception as ex:
         self.assertIn('java.lang.NumberFormatException', str(ex))
Beispiel #22
0
def initParameters(Framework):
    try:
        parameter = Framework.getParameter(PARAM_INACTIVE_TIMEOUT)
        logger.debug("Parameter for InactiveTimeout:", parameter)
        global inactiveTimeout
        inactiveTimeout = Integer.parseInt(parameter) * DAY
    except:
        pass
    logger.debug("InactiveTimeout value(ms):", inactiveTimeout)

    try:
        parameter = Framework.getParameter(PARAM_DELETE_TIMEOUT)
        logger.debug("Parameter for deleteTimeout:", parameter)
        global  deleteTimeout
        deleteTimeout = Integer.parseInt(parameter) * DAY
    except:
        pass
    logger.debug("DeleteTimeout value(ms):", deleteTimeout)

    try:
        parameter = Framework.getParameter(PARAM_CLEANUP_TIMEOUT)
        logger.debug("Parameter for CleanupTimeout:", parameter)
        global  cleanupTimeout
        cleanupTimeout = Integer.parseInt(parameter) * DAY
    except:
        pass

    logger.debug("CleanupTimeout value:(ms):", cleanupTimeout)
    #make sure the clean up timeout is not shorter than the sum of inactive timeout and delete timeout
    minCleanupTimeout = inactiveTimeout + deleteTimeout
    if cleanupTimeout < minCleanupTimeout:
        cleanupTimeout = minCleanupTimeout

    try:
        parameter = Framework.getParameter(PARAM_MOONWALK_SLEEP)
        logger.debug("Parameter for moonwalkSleep:", parameter)
        global  moonwalkSleep
        moonwalkSleep = Integer.parseInt(parameter)
    except:
        pass

    try:
        parameter = Framework.getParameter(PARAM_IS_COLLECT_DATA_CENTER_IP)
        logger.debug("Parameter for isCollectDataCenterIP:", parameter)
        global  isCollectDataCenterIP
        isCollectDataCenterIP = Boolean.parseBoolean(parameter)
    except:
        pass

    try:
        parameter = Framework.getParameter(PARAM_IS_REPORT_DELETE_IP)
        logger.debug("Parameter for isReportDeleteIP:", parameter)
        global  isReportDeleteIP
        isReportDeleteIP = Boolean.parseBoolean(parameter)
    except:
        pass

    logger.debug("Final value for parameters:")
    logger.debug("inactiveTimeout:", inactiveTimeout)
    logger.debug("deleteTimeout:", deleteTimeout)
    logger.debug("cleanupTimeout:", cleanupTimeout)
    logger.debug("moonwalkSleep:", moonwalkSleep)
    logger.debug("isCollectDataCenterIP:", isCollectDataCenterIP)
    logger.debug("isReportDeleteIP:", isReportDeleteIP)
    def discover_private(self):
        maxPorts = Integer.parseInt(self.getParameterValue('maxPorts'))
        tcpOnly = Boolean.parseBoolean(self.getParameterValue('tcpOnly'))

        #WE ALWAYS CHECK ONLY ONE DIRECTION SINCE WE ALWAYS REPORT FLOWS IN BOTH DIRECTION SO
        #WE CAN COUNT CLIENTS ONLY ON ONE SIDE
        #WE ASSUME THAT NETFLOW ALWAYS REPORTS CONNECTIONS IN BOTH DIRECTIONS SO WE WILL GET
        #OCTETS AND PACKETS COUNT ALWAYS
        query = ' select SrcAddr ,DstAddr ,DstPort ,count(*) cnt, sum(dPkts) dPkts, sum(dOctets) dOctets, Prot,'
        query = query + ' case when Port is NULL then 0 else 1 end ListenPort  '
        query = query + ' from Agg_V5 left join Port_Process on DstAddr=ipaddress and DstPort=port and Prot = Protocol and listen '
        if tcpOnly:
            query = query + ' where Prot=6 '
        query = query + ' group by SrcAddr, DstAddr, DstPort '
        #for each ip -> ip traffic we first wnat get ports that are listen, than which have more clients
        #after all ports which have more traffic
        query = query + ' order by SrcAddr, DstAddr, ListenPort desc, cnt desc, dOctets desc, dPkts desc'

        #here Prot is asc since TCP ports have higher priority on UDP ports
        query = query + ', Prot asc '

        conn = self.Framework.getProbeDatabaseConnection('TCPDISCOVERY')
        st = None
        result = None
        try:
            st = conn.createStatement()
            result = st.executeQuery(query)
            currSrcAddr = None
            portsSet = StringVector()
            currDstAddr = None
            currLinkID = None
            octets = 0
            packets = 0
            dataFound = 0
            while result.next():
                dataFound = 1
                srcAddr = str(result.getString('SrcAddr'))
                dstAddr = str(result.getString('DstAddr'))
                dstPort = result.getString('DstPort')
                cnt = result.getString('cnt')
                listenPort = result.getInt('ListenPort')

                if not self.isServerPort(cnt, listenPort, dstPort):
                    continue

                if not self.shouldInclude(srcAddr, 0):
                    continue

                if not self.shouldInclude(dstAddr, 1):
                    continue

                linkID = self.createLinkID(srcAddr, dstAddr)

                if currLinkID == linkID:
                    octets = octets + result.getInt('dOctets')
                    packets = packets + result.getInt('dPkts')
                    if portsSet.size() < maxPorts:
                        portsSet.add(dstPort)
                    continue
                elif currLinkID != None:
                    self.addTraffic(currSrcAddr, currDstAddr, portsSet, octets, packets)

                currLinkID = linkID
                currSrcAddr = srcAddr
                currDstAddr = dstAddr
                portsSet = StringVector()
                portsSet.add(dstPort)
                octets = result.getInt('dOctets')
                packets = result.getInt('dPkts')

            if not dataFound:
                self.Framework.reportWarning("No data to process, please check if Host Resources jobs had already run")
            if currLinkID != None:
                self.addTraffic(currSrcAddr, currDstAddr, portsSet, octets, packets)
        finally:
            if result != None:
                try:
                    result.close
                except:
                    pass
            conn.close(st)
            conn.close()
Beispiel #24
0
import sys
from java.lang import Integer
from com.m1.ems.mgmt import ManagementContainer

container = ManagementContainer.getInstance()
cm = container.getClientManager()

custID = Integer.parseInt(sys.argv[1])
name = "Fake"
address = "fake"
version = "1.0.0.0"

# Generate a registration key for this customer, this display name and this address
regKey = cm.registerClient(custID, name, "VaultBox", address, 0)
print regKey

cm.setClientVersion(regKey, version);

rcm = container.getReplicationConfigManager()
vb = rcm.createVaultBox(address, name, regKey, custID);

if not vb:
    print "Error!"
else:    
    repInfo = rcm.getReplicationInformation(custID)    
    if not repInfo.getSftpPassword():
        repInfo.setSftpPassword( vb.getRegistrationKey() )
        if not rcm.saveReplicationInformation( repInfo ):
            print "Unable to update replication info"