Python past.builtins.basestring() Examples

The following are 30 code examples of past.builtins.basestring(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module past.builtins , or try the search function .
Example #1
Source File: netflow.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, fdesc, pcap_filter=None):
        """Creates the NetFlow object.

        fdesc: a file-like object or a filename
        pcap_filter: a PCAP filter to use with nfdump

        """
        cmd = ["nfdump", "-aq", "-o", self.fmt]
        cmdkargs = {}
        if isinstance(fdesc, basestring):
            with open(fdesc, 'rb') as fde:
                if fde.read(2) not in utils.FileOpener.FILE_OPENERS_MAGIC:
                    cmd.extend(["-r", fdesc])
                else:
                    cmdkargs["stdin"] = utils.open_file(fdesc)
        else:
            cmdkargs["stdin"] = fdesc
        if pcap_filter is not None:
            cmd.append(pcap_filter)
        super(NetFlow, self).__init__(cmd, cmdkargs) 
Example #2
Source File: tiny.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def searchfile(self, fname=None, scripts=None):
        """Search shared files from a file name (either a string or a
        regexp), only from scripts using the "ls" NSE module.

        """
        q = Query()
        if fname is None:
            fname = q.filename.exists()
        else:
            fname = self._searchstring_re(q.filename, fname)
        if scripts is None:
            return q.ports.any(q.scripts.any(q.ls.volumes.any(
                q.files.any(fname)
            )))
        if isinstance(scripts, basestring):
            scripts = [scripts]
        if len(scripts) == 1:
            return q.ports.any(q.scripts.any(
                (q.id == scripts[0]) &
                q.ls.volumes.any(q.files.any(fname))
            ))
        return q.ports.any(q.scripts.any(
            q.id.one_of(scripts) &
            q.ls.volumes.any(q.files.any(fname))
        )) 
Example #3
Source File: tiny.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def rec2internal(cls, rec):
        """Given a record as presented to the user, fixes it before it can be
inserted in the database.

        """
        rec = deepcopy(rec)
        try:
            rec['addr'] = cls.ip2internal(rec['addr'])
        except (KeyError, ValueError):
            pass
        for fld in ['firstseen', 'lastseen']:
            if fld not in rec:
                continue
            if isinstance(rec[fld], datetime):
                rec[fld] = utils.datetime2timestamp(rec[fld])
            elif isinstance(rec[fld], basestring):
                rec[fld] = utils.datetime2timestamp(
                    utils.all2datetime(rec[fld])
                )
            if '_id' in rec:
                del rec['_id']
        return rec 
Example #4
Source File: __init__.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def distinct(self, field, flt=None, sort=None, limit=None, skip=None,
                 **kargs):
        """This method produces a generator of distinct values for a given
field.

        """
        if isinstance(field, basestring):
            field = self.fields[field]
        if flt is None:
            flt = self.flt_empty
        sort = [
            (self.fields[key] if isinstance(key, basestring) else key, way)
            for key, way in sort or []
        ]
        req = self._distinct_req(field, flt, **kargs)
        for key, way in sort:
            req = req.order_by(key if way >= 0 else desc(key))
        if skip is not None:
            req = req.offset(skip)
        if limit is not None:
            req = req.limit(limit)
        return (next(iter(viewvalues(res))) for res in self.db.execute(req)) 
Example #5
Source File: serializer.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def validate(self, value, session=None):
        # Check that the assigned value is a subclass of the nested class.
        nested_cls = SerializedObject.ImplementationByClass(self.nested)

        # Direct assignment of the correct type.
        if value.__class__ is nested_cls:
            return value

        # Assign a dict to this object, parse from primitive.
        elif isinstance(value, (dict, basestring, int, int, float)):
            return nested_cls.from_primitive(value, session=session)

        # A subclass is assigned.
        elif issubclass(value.__class__, nested_cls):
            return value

        raise ValueError("value is not valid.") 
Example #6
Source File: utils.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def all2datetime(arg):
    """Return a datetime object from an int (timestamp) or an iso
    formatted string '%Y-%m-%d %H:%M:%S'.

    """
    if isinstance(arg, datetime.datetime):
        return arg
    if isinstance(arg, basestring):
        for fmt in ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f',
                    '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f']:
            try:
                return datetime.datetime.strptime(arg, fmt)
            except ValueError:
                pass
        raise ValueError('time data %r does not match standard formats' % arg)
    if isinstance(arg, (int_types, float)):
        return datetime.datetime.fromtimestamp(arg)
    raise TypeError("%s is of unknown type." % repr(arg)) 
Example #7
Source File: utils.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def normalize_props(props, braces=True):
    """Returns a normalized property list/dict so that (roughly):
        - a list gives {k: "{k}"} if braces=True, {k: "k"} otherwise
        - a dict gives {k: v if v is not None else "{%s}" % v} if braces=True,
                       {k: v if v is not Node else "%s" % v} otherwise
    """
    if not isinstance(props, dict):
        props = dict.fromkeys(props)
    # Remove braces if necessary
    if not braces:
        for key, value in viewitems(props):
            if (isinstance(value, basestring) and value.startswith('{') and
                    value.endswith('}')):
                props[key] = value[1:-1]
    form = "{%s}" if braces else "%s"
    props = dict(
        (key, (value if isinstance(value, basestring) else
               (form % key) if value is None else
               str(value))) for key, value in viewitems(props)
    )
    return props 
Example #8
Source File: utils.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def country_unalias(country):
    """Takes either a country code (or an iterator of country codes)
    and returns either a country code or a list of country codes.

    Current aliases are:

      - "UK": alias for "GB".

      - "EU": alias for a list containing the list of the country
        codes of the European Union member states. It also includes
        "EU" itself, because that was a valid "country" code in
        previous Maxmind GeoIP databases.

    """
    if isinstance(country, basestring):
        return COUNTRY_ALIASES.get(country, country)
    if hasattr(country, '__iter__'):
        return functools.reduce(
            lambda x, y: x + (y if isinstance(y, list) else [y]),
            (country_unalias(country_elt) for country_elt in country),
            [],
        )
    return country 
Example #9
Source File: argus.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, fdesc, pcap_filter=None):
        """Creates the Argus object.

        fdesc: a file-like object or a filename
        pcap_filter: a PCAP filter to use with racluster
        """
        cmd = ["racluster", "-u", "-n", "-c", ",", "-m"]
        cmd.extend(self.aggregation)
        cmd.append("-s")
        cmd.extend(self.fields)
        cmd.extend(["-r", fdesc if isinstance(fdesc, basestring) else "-"])
        if pcap_filter is not None:
            cmd.extend(["--", pcap_filter])
        super(Argus, self).__init__(
            cmd, {} if isinstance(fdesc, basestring) else {"stdin": fdesc},
        )
        self.fdesc.readline() 
Example #10
Source File: utils.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def get_init_flt(dbase):
    """Return a filter corresponding to the current user's
    privileges.

    """
    init_queries = dict([key, _parse_query(dbase, value)]
                        for key, value in viewitems(config.WEB_INIT_QUERIES))
    user = get_user()
    if user in init_queries:
        return init_queries[user]
    if isinstance(user, basestring) and '@' in user:
        realm = user[user.index('@'):]
        if realm in init_queries:
            return init_queries[realm]
    if config.WEB_PUBLIC_SRV:
        return dbase.searchcategory(["Shared", get_anonymized_user()])
    return _parse_query(dbase, config.WEB_DEFAULT_INIT_QUERY) 
Example #11
Source File: plugin_polling_generic_snmp.py    From panoptes with Apache License 2.0 6 votes vote down vote up
def _get_metrics_groups_with_oid(self, oid_name):
        """
        Given an oid_name, returns a set of the names of all metrics groups which use that oid.
        Args:
            oid_name: The name of the oid to query as defined in the oid map.
        Returns:
            A set of the names (as defined in the metrics_groups map) of all metrics groups that reference that oid.
        """
        metrics_groups = set()
        for metrics_group_map in self._config[u"metrics_groups"]:
            for metric_value in list(metrics_group_map[u"metrics"].values()):
                if isinstance(metric_value[u"value"], basestring):
                    if oid_name in metric_value[u"value"]:
                        metrics_groups.add(metrics_group_map[u"group_name"])
            for dimension_value in list(metrics_group_map[u"dimensions"].values()):
                if isinstance(dimension_value[u"value"], basestring):
                    if oid_name in dimension_value[u"value"]:
                        metrics_groups.add(metrics_group_map[u"group_name"])
        return metrics_groups 
Example #12
Source File: session.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _set_live(self, live, _):
        if live is not None and not self.live:
            if isinstance(live, basestring):
                live = [live]

            # Default is to use Memory analysis.
            if len(live) == 0:
                mode = "Memory"
            elif len(live) == 1:
                mode = live[0]
            else:
                raise RuntimeError(
                    "--live parameter should specify only one mode.")

            live_plugin = self.session.plugins.live(mode=mode)
            live_plugin.live()

            # When the session is destroyed, close the live plugin.
            self.session.register_flush_hook(self, live_plugin.close)

        return live 
Example #13
Source File: util.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _cast(value, return_type=None):
    """
    Function takes value and data type to cast.
    Returns result of casting and success status
    """

    if not return_type or value is None:
        return value, True


    try:
        if return_type == bool and isinstance(value, future_basestring):
            if value.lower() == "false":
                return False, True
            if value.lower() == "true":
                return True, True
    except Exception:
        pass

    try:
        return return_type(value), True
    except Exception:
        pass

    return None, False 
Example #14
Source File: session.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def GetRenderer(self, output=None):
        """Get a renderer for this session.

        If a renderer is currently active we just reuse it, otherwise we
        instantiate the renderer specified in self.GetParameter("format").
        """
        # Reuse the current renderer.
        if self.renderers and output is None:
            return self.renderers[-1]

        ui_renderer = self.GetParameter("format", "text")
        if isinstance(ui_renderer, basestring):
            ui_renderer_cls = renderer.BaseRenderer.ImplementationByName(
                ui_renderer)
            ui_renderer = ui_renderer_cls(session=self, output=output)

        return ui_renderer 
Example #15
Source File: io_manager_test.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def testDirectoryIOManager(self):
        manager = io_manager.DirectoryIOManager(
            self.temp_directory,
            session=self.MakeUserSession())

        # Cant decode from json.
        self.assertEqual(manager.GetData("foo"), None)
        self.assertEqual(manager.GetData("foo", raw=True),
                         b"hello")

        # Test ListFiles().
        self.assertListEqual(sorted(manager.ListFiles()),
                             ["bar", "foo"])

        # Storing a data structure.
        data = dict(a=1)
        manager.StoreData("baz", data)
        self.assertDictEqual(manager.GetData("baz"),
                             data)

        self.assertTrue(
            isinstance(manager.GetData("baz", raw=True), basestring)) 
Example #16
Source File: intel.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def __getitem__(self, item):
        """Get a particular descriptor.

        Descriptors can be requested by name (e.g. VirtualAddressDescriptor) or
        index (e.g. -1).
        """
        if isinstance(item, basestring):
            for descriptor_cls, args, kwargs in self.descriptors:
                if descriptor_cls.__name__ == item:
                    kwargs["session"] = self.session
                    return descriptor_cls(*args, **kwargs)

            return obj.NoneObject("No descriptor found.")
        try:
            cls, args, kwargs = self.descriptors[item]
            kwargs["session"] = self.session
            return cls(*args, **kwargs)
        except KeyError:
            return obj.NoneObject("No descriptor found.") 
Example #17
Source File: common.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, filename, filesystem=u"API", path_sep=None):
        super(FileSpec, self).__init__()

        if isinstance(filename, FileSpec):
            # Copy the other file spec.
            self.name = filename.name
            self.filesystem = filename.filesystem
            self.path_sep = filename.path_sep

        elif isinstance(filename, basestring):
            self.name = utils.SmartUnicode(filename)
            self.filesystem = filesystem
            self.path_sep = path_sep or self.default_path_sep

        else:
            raise TypeError("Filename must be a string or file spec not %s." % type(
                filename)) 
Example #18
Source File: registry.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def open_key(self, key=""):
        """Opens a key.

        Args:
           key: A string path to the key (separated with / or \\) or a list of
              path components (useful if the keyname contains /).
        """
        if isinstance(key, basestring):
            # / can be part of the key name...
            key = [_f for _f in re.split(r"[\\/]", key) if _f]

        result = self.root
        for component in key:
            result = result.open_subkey(component)

        return result 
Example #19
Source File: core.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def render(self, renderer):
        if isinstance(self.plugin_args.target, basestring):
            self.plugin_args.target = self.profile.Object(
                type_name=self.plugin_args.target,
                offset=self.plugin_args.offset,
                vm=self.plugin_args.address_space)

        item = self.plugin_args.target

        if isinstance(item, obj.Pointer):
            item = item.deref()

        if isinstance(item, obj.Struct):
            return self.render_Struct(renderer, item)

        self.session.plugins.p(self.plugin_args.target).render(renderer) 
Example #20
Source File: __init__.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def _searchstring_list(field, value, neg=False, map_=None):
        if not isinstance(value, basestring) and hasattr(value, '__iter__'):
            if map_ is not None:
                value = [map_(elt) for elt in value]
            if neg:
                return field.notin_(value)
            return field.in_(value)
        if map_ is not None:
            value = map_(value)
        if neg:
            return field != value
        return field == value 
Example #21
Source File: printkey.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def render(self, renderer):
        renderer.format("Legend: (S) = Stable   (V) = Volatile\n\n")
        for reg, key in self.list_keys():
            self.session.report_progress(
                "Printing %s", lambda key=key: key.Path)

            if key:
                renderer.format("----------------------------\n")
                renderer.format("Registry: {0}\n", reg.Name)
                renderer.format("Key name: {0} {1} @ {2:addrpad}\n", key.Name,
                                self.voltext(key), key.obj_vm.vtop(int(key)))

                renderer.format("Last updated: {0}\n", key.LastWriteTime)
                renderer.format("\n")
                renderer.format("Subkeys:\n")

                for subkey in key.subkeys():
                    if not subkey.Name:
                        renderer.format(
                            "  Unknown subkey: {0}\n", subkey.Name.reason)
                    else:
                        renderer.format(u"  {1} {0}\n",
                                        subkey.Name, self.voltext(subkey))

                renderer.format("\n")
                renderer.format("Values:\n")
                for value in list(key.values()):
                    renderer.format("{0:addrpad} ", value.obj_vm.vtop(value))
                    if value.Type == 'REG_BINARY':
                        data = value.DecodedData
                        if isinstance(data, basestring):
                            renderer.format(
                                u"{0:width=13} {1:width=15} : {2}\n",
                                value.Type, value.Name, self.voltext(value))
                            utils.WriteHexdump(renderer, value.DecodedData)
                    else:
                        renderer.format(
                            u"{0:width=13} {1:width=15} : {2} {3}\n",
                            value.Type, value.Name, self.voltext(value),
                            utils.SmartUnicode(value.DecodedData).strip()) 
Example #22
Source File: pygraphistry.py    From pygraphistry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def certificate_validation(value=None):
        """Enable/Disable SSL certificate validation (True, False).
        Also set via environment variable GRAPHISTRY_CERTIFICATE_VALIDATION."""
        if value is None:
            return PyGraphistry._config['certificate_validation']

        # setter
        v = bool(strtobool(value)) if isinstance(value, basestring) else value
        if v == False:
            requests.packages.urllib3.disable_warnings()
        PyGraphistry._config['certificate_validation'] = v 
Example #23
Source File: test_load_all_json.py    From python-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_from_file(self):
        failed_json_files = []
        processed_files = []

        for language in DBVuln.get_all_languages():

            json_path = os.path.join(DBVuln.DB_PATH, language)

            for _fname in os.listdir(json_path):
                _file_path = os.path.join(json_path, _fname)

                if os.path.isdir(_file_path):
                    continue

                try:
                    DBVuln.LANG = language
                    dbv = DBVuln.from_file(_file_path)
                except:
                    failed_json_files.append(_fname)
                    continue

                processed_files.append(_fname)

                self.assertIsInstance(dbv.title, basestring)
                self.assertIsInstance(dbv.description, basestring)
                self.assertIsInstance(dbv.id, int)
                self.assertIsInstance(dbv.severity, basestring)
                self.assertIsInstance(dbv.wasc, (type(None), list))
                self.assertIsInstance(dbv.tags, (type(None), list))
                self.assertIsInstance(dbv.cwe, (type(None), list))
                self.assertIsInstance(dbv.owasp_top_10, (type(None), dict))
                self.assertIsInstance(dbv.fix_effort, int)
                self.assertIsInstance(dbv.fix_guidance, basestring)

                for ref in dbv.references:
                    self.assertIsInstance(ref, Reference)

            self.assertEqual(failed_json_files, [])
            self.assertGreater(len(processed_files), 20) 
Example #24
Source File: api.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def get_active_modes(self, cls):
        """Calculate the declared modes under which the plugin is active."""
        modes = set()
        for subclass in cls.__mro__:
            mode = getattr(subclass, "mode", None)

            if isinstance(mode, basestring):
                modes.add(mode)

            elif isinstance(mode, (list, tuple)):
                modes.update(mode)

        return sorted(modes) 
Example #25
Source File: profile_index.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def LookupProfile(self, symbols):
        """Returns which profiles in the index match a dict of symbols.

        Returns:
            A list of tuples of (profile, num_matched_traits).
        """
        profiles = []
        try:
            relative_symbols = self.RelativizeSymbols(symbols.copy())
        except ValueError as e:
            self.session.logging.debug(str(e))
            return []

        for profile, traits in six.iteritems(self.traits):
            matched_traits = 0

            for trait in traits:
                # A trait is a list of symbol-offset tuples.
                match = all([relative_symbols.get(symbol) == offset
                             for (symbol, offset) in trait
                             if isinstance(symbol, basestring)])
                if match:
                    matched_traits += 1

            if matched_traits > 0:
                profiles.append((profile, matched_traits))
        return profiles 
Example #26
Source File: activecli.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def _display_xml_scan(scan, out=sys.stdout):
    if 'scaninfos' in scan and scan['scaninfos']:
        for k in scan['scaninfos'][0]:
            scan['scaninfo.%s' % k] = scan['scaninfos'][0][k]
        del scan['scaninfos']
    for k in ['version', 'start', 'startstr', 'args', 'scanner',
              'xmloutputversion', 'scaninfo.type', 'scaninfo.protocol',
              'scaninfo.numservices', 'scaninfo.services']:
        if k not in scan:
            scan[k] = ''
        elif isinstance(scan[k], basestring):
            scan[k] = scan[k].replace('"', '"').replace('--', '--')
    out.write('<!DOCTYPE nmaprun PUBLIC '
              '"-//IDN nmap.org//DTD Nmap XML 1.04//EN" '
              '"https://svn.nmap.org/nmap/docs/nmap.dtd">\n'
              '<?xml-stylesheet '
              'href="file:///usr/local/bin/../share/nmap/nmap.xsl" '
              'type="text/xsl"?>\n'
              '<!-- %(scanner)s %(version)s scan initiated %(startstr)s '
              'as: %(args)s -->\n'
              '<nmaprun scanner="%(scanner)s" args="%(args)s" '
              'start="%(start)s" startstr="%(startstr)s" '
              'version="%(version)s" '
              'xmloutputversion="%(xmloutputversion)s">\n'
              '<scaninfo type="%(scaninfo.type)s" '
              'protocol="%(scaninfo.protocol)s" '
              'numservices="%(scaninfo.numservices)s" '
              'services="%(scaninfo.services)s"/>\n' % scan) 
Example #27
Source File: graph_view.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connectPorts(self, srcNode, outputName, tgtNode, inputName):

        if isinstance(srcNode, Node):
            sourceNode = srcNode
        elif isinstance(srcNode, basestring):
            sourceNode = self.getNode(srcNode)
            if not sourceNode:
                raise Exception("Node not found:" + str(srcNode))
        else:
            raise Exception("Invalid srcNode:" + str(srcNode))


        sourcePort = sourceNode.getPort(outputName)
        if not sourcePort:
            raise Exception("Node '" + sourceNode.getName() + "' does not have output:" + outputName)


        if isinstance(tgtNode, Node):
            targetNode = tgtNode
        elif isinstance(tgtNode, basestring):
            targetNode = self.getNode(tgtNode)
            if not targetNode:
                raise Exception("Node not found:" + str(tgtNode))
        else:
            raise Exception("Invalid tgtNode:" + str(tgtNode))

        targetPort = targetNode.getPort(inputName)
        if not targetPort:
            raise Exception("Node '" + targetNode.getName() + "' does not have input:" + inputName)

        connection = Connection(self, sourcePort.outCircle(), targetPort.inCircle())
        self.addConnection(connection, emitSignal=False)

        return connection

    ################################################
    ## Events 
Example #28
Source File: activecli.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def _display_gnmap_scan(scan, out=sys.stdout):
    if 'scaninfos' in scan and scan['scaninfos']:
        for k in scan['scaninfos'][0]:
            scan['scaninfo.%s' % k] = scan['scaninfos'][0][k]
        del scan['scaninfos']
    for k in ['version', 'startstr', 'args']:
        if k not in scan:
            scan[k] = ''
        elif isinstance(scan[k], basestring):
            scan[k] = scan[k].replace('"', '&quot;').replace('--', '-&#45;')
    out.write('# Nmap %(version)s scan initiated %(startstr)s as: %(args)s\n') 
Example #29
Source File: target.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, asnum, categories=None, rand=True, maxnbr=None,
                 state=None):
        if isinstance(asnum, basestring) and asnum.upper().startswith('AS'):
            asnum = int(asnum[2:])
        else:
            asnum = int(asnum)
        super(TargetAS, self).__init__(
            geoiputils.get_ranges_by_asnum(asnum), rand=rand, maxnbr=maxnbr,
            state=state, name='AS-%d' % asnum, categories=categories,
        ) 
Example #30
Source File: blockexplorer.py    From api-v1-client-python with MIT License 5 votes vote down vote up
def get_multi_address(addresses, filter=None, limit=None, offset=None, api_code=None):
    """Get aggregate summary for multiple addresses including overall balance, per address balance
     and list of relevant transactions.

    :param tuple addresses: addresses(xpub or base58) to look up
    :param FilterType filter: the filter for transactions selection (optional)
    :param int limit: limit number of transactions to fetch (optional)
    :param int offset: number of transactions to skip when fetch (optional)
    :param str api_code: Blockchain.info API code (optional)
    :return: an instance of :class:`MultiAddress` class
    """

    if isinstance(addresses, basestring):
        resource = 'multiaddr?active=' + addresses
    else:
        resource = 'multiaddr?active=' + '|'.join(addresses)
    if filter is not None:
        if isinstance(filter, FilterType):
            resource += '&filter=' + str(filter.value)
        else:
            raise ValueError('Filter must be of FilterType enum')
    if limit is not None:
        resource += '&limit=' + str(limit)
    if offset is not None:
        resource += '&offset=' + str(offset)
    if api_code is not None:
        resource += '&api_code=' + api_code
    response = util.call_api(resource)
    json_response = json.loads(response)
    return MultiAddress(json_response)