當前位置: 首頁>>代碼示例>>Python>>正文


Python results.Message方法代碼示例

本文整理匯總了Python中splunklib.results.Message方法的典型用法代碼示例。如果您正苦於以下問題:Python results.Message方法的具體用法?Python results.Message怎麽用?Python results.Message使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在splunklib.results的用法示例。


在下文中一共展示了results.Message方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_current_splunk_time

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def get_current_splunk_time(splunk_service):
    t = datetime.utcnow() - timedelta(days=3)
    time = t.strftime(SPLUNK_TIME_FORMAT)
    kwargs_oneshot = {'count': 1, 'earliest_time': time}
    searchquery_oneshot = '| gentimes start=-1 | eval clock = strftime(time(), "%Y-%m-%dT%H:%M:%S")' \
                          ' | sort 1 -_time | table clock'

    oneshotsearch_results = splunk_service.jobs.oneshot(searchquery_oneshot, **kwargs_oneshot)

    reader = results.ResultsReader(oneshotsearch_results)
    for item in reader:
        if isinstance(item, results.Message):
            return item.message["clock"]
        if isinstance(item, dict):
            return item["clock"]
    raise ValueError('Error: Could not fetch Splunk time') 
開發者ID:demisto,項目名稱:content,代碼行數:18,代碼來源:SplunkPy.py

示例2: parse_batch_of_results

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def parse_batch_of_results(current_batch_of_results, max_results_to_add, app):
    parsed_batch_results = []
    batch_dbot_scores = []
    results_reader = results.ResultsReader(io.BufferedReader(ResponseReaderWrapper(current_batch_of_results)))
    for item in results_reader:
        if isinstance(item, results.Message):
            if "Error in" in item.message:
                raise ValueError(item.message)
            parsed_batch_results.append(convert_to_str(item.message))

        elif isinstance(item, dict):
            if demisto.get(item, 'host'):
                batch_dbot_scores.append({'Indicator': item['host'], 'Type': 'hostname',
                                          'Vendor': 'Splunk', 'Score': 0, 'isTypedIndicator': True})
            if app:
                item['app'] = app
            # Normal events are returned as dicts
            parsed_batch_results.append(item)

        if len(parsed_batch_results) >= max_results_to_add:
            break
    return parsed_batch_results, batch_dbot_scores 
開發者ID:demisto,項目名稱:content,代碼行數:24,代碼來源:SplunkPy.py

示例3: _process_result

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def _process_result(self, result, **kwargs):
        if isinstance(result, results.Message):
            if kwargs['verbose']:
                print(f"Message: {result}")
            return None

        if isinstance(result, dict):
            # Remove internal fields if requested
            if kwargs['internal_fields'] is False:
                for field in [key for key in result.keys() if key.startswith('_')]:
                    result.pop(field)
            elif isinstance(kwargs['internal_fields'], str):
                for field in list(map(lambda x: x.strip(), kwargs['internal_fields'].split(','))):
                    result.pop(field)

        return result 
開發者ID:target,項目名稱:huntlib,代碼行數:18,代碼來源:splunk.py

示例4: messages

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def messages(self):
        """Returns the collection of service messages.

        :return: A :class:`Collection` of :class:`Message` entities.
        """
        return Collection(self, PATH_MESSAGES, item=Message) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:8,代碼來源:client.py

示例5: results

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def results(self, **query_params):
        """Returns a streaming handle to this job's search results. To get a
        nice, Pythonic iterator, pass the handle to :class:`splunklib.results.ResultsReader`,
        as in::

            import splunklib.client as client
            import splunklib.results as results
            from time import sleep
            service = client.connect(...)
            job = service.jobs.create("search * | head 5")
            while not job.is_done():
                sleep(.2)
            rr = results.ResultsReader(job.results())
            for result in rr:
                if isinstance(result, results.Message):
                    # Diagnostic messages may be returned in the results
                    print '%s: %s' % (result.type, result.message)
                elif isinstance(result, dict):
                    # Normal events are returned as dicts
                    print result
            assert rr.is_preview == False

        Results are not available until the job has finished. If called on
        an unfinished job, the result is an empty event set.

        This method makes a single roundtrip
        to the server, plus at most two additional round trips if
        the ``autologin`` field of :func:`connect` is set to ``True``.

        :param query_params: Additional parameters (optional). For a list of valid
            parameters, see `GET search/jobs/{search_id}/results
            <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fresults>`_.
        :type query_params: ``dict``

        :return: The ``InputStream`` IO handle to this job's results.
        """
        query_params['segmentation'] = query_params.get('segmentation', 'none')
        return self.get("results", **query_params).body 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:40,代碼來源:client.py

示例6: _parse_results

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def _parse_results(self, handle):
        """ Wraps output from Splunk searches with the Splunk ResultsReader.
        Splunk typically retrieves events debug statements, errors through the same stream.
        Debug/Info messages will be displayed and actual results

        :param handle: Splunk search job generator
        """
        result_reader = ResultsReader(handle)
        for result in result_reader:

            # Diagnostic messages may be returned in the results
            if isinstance(result, Message):
                logger.debug('[{}] {}'.format(result.type, result.message))

            # Normal events are returned as dicts
            elif isinstance(result, dict):
                result = dict(result)
                if '_time' in result:
                    result['_time'] = SplunkAbstraction._to_datetime(result['_time'])
                yield {
                    'time': result['_time'] if '_time' in result else '',
                    'metadata': {k: v for k, v in result.items() if k.startswith('_')},
                    'state': {k: v for k, v in result.items() if not k.startswith('_')}
                }

            else:
                logger.warning('Unknown result type in _parse_results: {}'.format(result))

        assert result_reader.is_preview is False 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:31,代碼來源:splunk.py

示例7: splunk_results_command

# 需要導入模塊: from splunklib import results [as 別名]
# 或者: from splunklib.results import Message [as 別名]
def splunk_results_command(service):
    res = []
    sid = demisto.args().get('sid', '')
    try:
        job = service.job(sid)
    except HTTPError as error:
        if error.message == 'HTTP 404 Not Found -- Unknown sid.':
            demisto.results("Found no job for sid: {}".format(sid))
        else:
            return_error(error.message, error)
    else:
        for result in results.ResultsReader(job.results()):
            if isinstance(result, results.Message):
                demisto.results({"Type": 1, "ContentsFormat": "json", "Contents": json.dumps(result.message)})
            elif isinstance(result, dict):
                # Normal events are returned as dicts
                res.append(result)

        demisto.results({"Type": 1, "ContentsFormat": "json", "Contents": json.dumps(res)}) 
開發者ID:demisto,項目名稱:content,代碼行數:21,代碼來源:SplunkPy.py


注:本文中的splunklib.results.Message方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。