How to use the cbapi.errors.ApiError function in cbapi

To help you get started, we’ve selected a few cbapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github carbonblack / cbapi-python / src / cbapi / psc / livequery / query.py View on Github external
def submit(self):
        """
        Submits this LiveQuery run.

        :return: A new ``Run`` instance containing the run's status
        """
        if self._query_token is not None:
            raise ApiError(
                "Query already submitted: token {0}".format(self._query_token)
            )

        if "sql" not in self._query_body:
            raise ApiError("Missing LiveQuery SQL")

        url = self._doc_class.urlobject.format(self._cb.credentials.org_key)
        resp = self._cb.post_object(url, body=self._query_body)

        return self._doc_class(self._cb, initial_data=resp.json())
github ctxis / cbrcli / cbrcli.py View on Github external
break
    except KeyboardInterrupt:
        print('%s' % (color("Caught ctrl+c. Use 'exit' or ctrl+d to quit", 'orange')))
        continue
    cmd = from_user.split(' ')[0]
    params = from_user.split(' ')[1:]
    try:
        params = [int(cmd)] + params
        cmd = "info"
    except ValueError:
        pass
    if not cmd and state['result']:
        cmd = 'next'
    try:
        out = getattr(cbcli_cmd, '_' + cmd.replace('-', '_'), cbcli_cmd._invalid_cmd)(cmd=cmd, params=params, state=state)
    except ApiError:
        print(color("Query timed out", 'red'))
        continue
    if out:
        print(color(out, 'red'))
github carbonblack / cbapi-python / src / cbapi / psc / query.py View on Github external
if kwargs.get("start", None) and kwargs.get("end", None):
            if kwargs.get("range", None):
                raise ApiError("cannot specify range= in addition to start= and end=")
            stime = kwargs["start"]
            if not isinstance(stime, str):
                stime = stime.isoformat()
            etime = kwargs["end"]
            if not isinstance(etime, str):
                etime = etime.isoformat()
            self._time_filter = {"start": stime, "end": etime}
        elif kwargs.get("range", None):
            if kwargs.get("start", None) or kwargs.get("end", None):
                raise ApiError("cannot specify start= or end= in addition to range=")
            self._time_filter = {"range": kwargs["range"]}
        else:
            raise ApiError("must specify either start= and end= or range=")
        return self
github carbonblack / cbapi-python / src / cbapi / psc / query.py View on Github external
def sort_by(self, key, direction="ASC"):
        """Sets the sorting behavior on a query's results.

        Example::

        >>> cb.select(BaseAlert).sort_by("name")

        :param key: the key in the schema to sort by
        :param direction: the sort order, either "ASC" or "DESC"
        :rtype: :py:class:`BaseAlertSearchQuery`
        """
        if direction not in DeviceSearchQuery.valid_directions:
            raise ApiError("invalid sort direction specified")
        self._sortcriteria = {"field": key, "order": direction}
        return self
github carbonblack / cbapi-python / src / cbapi / psc / alerts_query.py View on Github external
def set_group_ids(self, groupids):
        """
        Restricts the alerts that this query is performed on to the specified
        AppDefense-assigned alarm group IDs.

        :param groupids list: List of (integer) AppDefense-assigned alarm group IDs.
        :return: This instance.
        """
        if not all(isinstance(groupid, int) for groupid in groupids):
            raise ApiError("One or more invalid alarm group IDs")
        self._update_criteria("group_id", groupids)
        return self
github carbonblack / cbapi-python / src / cbapi / psc / threathunter / models.py View on Github external
def __init__(self, cb, model_unique_id=None, initial_data=None, report_id=None):
        """Creates a new IOC_V2 instance.

        :raise ApiError: if `initial_data` is `None`
        """
        if not initial_data:
            raise ApiError("IOC_V2 can only be initialized from initial_data")

        super(IOC_V2, self).__init__(cb, model_unique_id=initial_data.get(self.primary_key),
                                     initial_data=initial_data, force_init=False,
                                     full_doc=True)

        self._report_id = report_id
github carbonblack / cbapi-python / src / cbapi / psc / livequery / query.py View on Github external
def wrap_guard_query_change(self, q, **kwargs):
            if self._raw_query is not None and (kwargs or isinstance(q, Q)):
                raise ApiError("Cannot modify a raw query with structured parameters")
            if self._query is not None and isinstance(q, string_types):
                raise ApiError("Cannot modify a structured query with a raw parameter")
            return func(self, q, **kwargs)
github carbonblack / cbapi-python / examples / response / walk_children.py View on Github external
def main():
    parser = build_cli_parser("Walk the children of a given process")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--process", "-p", help="process GUID to walk", default='')
    group.add_argument("--query", "-q", help="walk the children of all processes matching this query")
    parser.add_argument("--children", "-c", default=15, help="number of children to fetch")
    args = parser.parse_args()
    c = get_cb_response_object(args)

    if args.process:
        try:
            procs = [c.select(Process, args.process, max_children=args.children, force_init=True)]
        except ObjectNotFoundError:
            print("Could not find process {0:s}".format(args.procss))
            return 1
        except ApiError as e:
            print("Encountered error retrieving process: {0:s}".format(str(e)))
            return 1
        except Exception as e:
            print("Encountered unknown error retrieving process: {0:s}".format(str(e)))
            return 1
    elif args.query:
        procs = c.select(Process).where(args.query).group_by("id").max_children(args.children)
    else:
        print("Requires either a --process or --query argument")
        parser.print_usage()
        return 2

    for root_proc in procs:
        if not root_proc.get('terminated'):
            duration = "still running"
        else:
github carbonblack / cbapi-python / src / cbapi / psc / threathunter / query.py View on Github external
:param kwargs: Arguments to construct a `solrq.Q` with
        :return: QueryBuilder object
        :rtype: :py:class:`QueryBuilder`
        """
        if isinstance(q, string_types):
            self.where(q)
        elif isinstance(q, Q) or kwargs:
            if kwargs:
                self._process_guid = self._process_guid or kwargs.get("process_guid")
                q = Q(**kwargs)
            if self._query is None:
                self._query = q
            else:
                self._query = self._query & q
        else:
            raise ApiError(".and_() only accepts strings or solrq.Q objects")

        return self