本文整理匯總了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')
示例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
示例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
示例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)
示例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
示例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
示例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)})