Python results.ResultsReader方法代碼示例- 純淨天空

文章推薦指數: 80 %
投票人數:10人

本文整理匯總了Python中splunklib.results.ResultsReader方法的典型用法代碼示例。

如果您正苦於以下問題:Python results.ResultsReader方法的具體用法? 當前位置:首頁>>代碼示例>>Python>>正文 本文整理匯總了Python中splunklib.results.ResultsReader方法的典型用法代碼示例。

如果您正苦於以下問題:Pythonresults.ResultsReader方法的具體用法?Pythonresults.ResultsReader怎麽用?Pythonresults.ResultsReader使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。

您也可以進一步了解該方法所在類splunklib.results的用法示例。

在下文中一共展示了results.ResultsReader方法的14個代碼示例,這些例子默認根據受歡迎程度排序。

您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。

示例1:export_report ▲點讚6 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defexport_report(self): job_obj=None forjinself.service.jobs: ifj.sid==self.sid: job_obj=j ifjob_objisNone: print("JobSID{}notfound.Diditexpire?".format(self.sid)) sys.exit() ifnotjob_obj.is_ready(): print("JobSID{}isstillprocessing." "Pleasewaittore-run".format(self.sir)) export_data=[] job_results=job_obj.results(rf=self.cols) forresultinresults.ResultsReader(job_results): export_data.append(result) self.write_csv(self.file,self.cols,export_data)開發者ID:PacktPublishing,項目名稱:Python-Digital-Forensics-Cookbook,代碼行數:22,代碼來源:splunk_connector.py 示例2:get_results ▲點讚6 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defget_results(self,job,count:int)->list:#pragma:nocover """ReturneventsfromafinishedJobasanarrayofdictionaries. Parameters ---------- job:Job Jobobjecttopullresultsfrom. Returns ------- list Theresultsofthesearch. """ importsplunklib.resultsasresults out=[resultforresultinresults.ResultsReader(job.results(count=count))] job.cancel() returnout開發者ID:yampelo,項目名稱:beagle,代碼行數:20,代碼來源:splunk_spl.py 示例3:get_current_splunk_time ▲點讚6 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defget_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='|gentimesstart=-1|evalclock=strftime(time(),"%Y-%m-%dT%H:%M:%S")'\ '|sort1-_time|tableclock' oneshotsearch_results=splunk_service.jobs.oneshot(searchquery_oneshot,**kwargs_oneshot) reader=results.ResultsReader(oneshotsearch_results) foriteminreader: ifisinstance(item,results.Message): returnitem.message["clock"] ifisinstance(item,dict): returnitem["clock"] raiseValueError('Error:CouldnotfetchSplunktime')開發者ID:demisto,項目名稱:content,代碼行數:18,代碼來源:SplunkPy.py 示例4:parse_batch_of_results ▲點讚6 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defparse_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))) foriteminresults_reader: ifisinstance(item,results.Message): if"Errorin"initem.message: raiseValueError(item.message) parsed_batch_results.append(convert_to_str(item.message)) elifisinstance(item,dict): ifdemisto.get(item,'host'): batch_dbot_scores.append({'Indicator':item['host'],'Type':'hostname', 'Vendor':'Splunk','Score':0,'isTypedIndicator':True}) ifapp: item['app']=app #Normaleventsarereturnedasdicts parsed_batch_results.append(item) iflen(parsed_batch_results)>=max_results_to_add: break returnparsed_batch_results,batch_dbot_scores開發者ID:demisto,項目名稱:content,代碼行數:24,代碼來源:SplunkPy.py 示例5:write_results ▲點讚6 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defwrite_results(job): """Writesresultstoatempfile""" reader=results.ResultsReader(job.results()) temp_filename="" withtempfile.NamedTemporaryFile(delete=False)astemp_file: temp_filename=temp_file.name writer=None forresultinreader: ifisinstance(result,dict): ifnotwriter: writer=csv.DictWriter(temp_file,fieldnames=result.keys(),dialect='excel') writer.writeheader() writer.writerow(result) returntemp_filename #endwrite_results開發者ID:ibmresilient,項目名稱:resilient-community-apps,代碼行數:18,代碼來源:splunk_client.py 示例6:results ▲點讚5 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defresults(self,**query_params): """Returnsastreaminghandletothisjob'ssearchresults.Togeta nice,Pythoniciterator,passthehandleto:class:`splunklib.results.ResultsReader`, asin:: importsplunklib.clientasclient importsplunklib.resultsasresults fromtimeimportsleep service=client.connect(...) job=service.jobs.create("search*|head5") whilenotjob.is_done(): sleep(.2) rr=results.ResultsReader(job.results()) forresultinrr: ifisinstance(result,results.Message): #Diagnosticmessagesmaybereturnedintheresults print'%s:%s'%(result.type,result.message) elifisinstance(result,dict): #Normaleventsarereturnedasdicts printresult assertrr.is_preview==False Resultsarenotavailableuntilthejobhasfinished.Ifcalledon anunfinishedjob,theresultisanemptyeventset. Thismethodmakesasingleroundtrip totheserver,plusatmosttwoadditionalroundtripsif the``autologin``fieldof:func:`connect`issetto``True``. :paramquery_params:Additionalparameters(optional).Foralistofvalid parameters,see`GETsearch/jobs/{search_id}/results `_. :typequery_params:``dict`` :return:The``InputStream``IOhandletothisjob'sresults. """ query_params['segmentation']=query_params.get('segmentation','none') returnself.get("results",**query_params).body開發者ID:remg427,項目名稱:misp42splunk,代碼行數:40,代碼來源:client.py 示例7:_parse_results ▲點讚5 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] def_parse_results(self,handle): """WrapsoutputfromSplunksearcheswiththeSplunkResultsReader. Splunktypicallyretrieveseventsdebugstatements,errorsthroughthesamestream. Debug/Infomessageswillbedisplayedandactualresults :paramhandle:Splunksearchjobgenerator """ result_reader=ResultsReader(handle) forresultinresult_reader: #Diagnosticmessagesmaybereturnedintheresults ifisinstance(result,Message): logger.debug('[{}]{}'.format(result.type,result.message)) #Normaleventsarereturnedasdicts elifisinstance(result,dict): result=dict(result) if'_time'inresult: result['_time']=SplunkAbstraction._to_datetime(result['_time']) yield{ 'time':result['_time']if'_time'inresultelse'', 'metadata':{k:vfork,vinresult.items()ifk.startswith('_')}, 'state':{k:vfork,vinresult.items()ifnotk.startswith('_')} } else: logger.warning('Unknownresulttypein_parse_results:{}'.format(result)) assertresult_reader.is_previewisFalse開發者ID:mitre,項目名稱:cascade-server,代碼行數:31,代碼來源:splunk.py 示例8:splunk_results_command ▲點讚5 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defsplunk_results_command(service): res=[] sid=demisto.args().get('sid','') try: job=service.job(sid) exceptHTTPErroraserror: iferror.message=='HTTP404NotFound--Unknownsid.': demisto.results("Foundnojobforsid:{}".format(sid)) else: return_error(error.message,error) else: forresultinresults.ResultsReader(job.results()): ifisinstance(result,results.Message): demisto.results({"Type":1,"ContentsFormat":"json","Contents":json.dumps(result.message)}) elifisinstance(result,dict): #Normaleventsarereturnedasdicts res.append(result) demisto.results({"Type":1,"ContentsFormat":"json","Contents":json.dumps(res)})開發者ID:demisto,項目名稱:content,代碼行數:21,代碼來源:SplunkPy.py 示例9:run ▲點讚5 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defrun(urlencoded,resp): HOST="splunkIP" PORT=8089 USERNAME="abhishekratan" PASSWORD="abhishekratan" #CreateaServiceinstanceandlogin service=client.connect( host=HOST, port=PORT, username=USERNAME, password=PASSWORD) kwargs_oneshot={"earliest_time":"-30d@d", "count":10 } url=unquote(urlencoded) oneshotsearch_results=service.jobs.oneshot(url,**kwargs_oneshot) reader=results.ResultsReader(oneshotsearch_results) result=[] foriteminreader: print(item) result.append(item) return_result=result result={"result":result} print(return_result) resp.body=json.dumps(result) returnreturn_result開發者ID:PacktPublishing,項目名稱:Practical-Network-Automation-Second-Edition,代碼行數:34,代碼來源:splunkquery.py 示例10:_retrieve_parallel_worker ▲點讚5 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] def_retrieve_parallel_worker(self,job,offset_queue,page_size,search_results): whilenotoffset_queue.empty(): offset=offset_queue.get() paginate_args=dict( count=page_size, offset=offset ) page_results=job.results(**paginate_args) forresultinresults.ResultsReader(page_results): ifisinstance(result,dict): search_results.append(result)開發者ID:target,項目名稱:huntlib,代碼行數:17,代碼來源:splunk.py 示例11:get_results ▲點讚5 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defget_results(job,limit): """Returnacollectionofresults""" reader=results.ResultsReader(job.results(count=limit)) return{"results":[rowforrowinreader]} #endget_results開發者ID:ibmresilient,項目名稱:resilient-community-apps,代碼行數:7,代碼來源:splunk_client.py 示例12:preview ▲點讚4 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defpreview(self,**query_params): """Returnsastreaminghandletothisjob'spreviewsearchresults. Unlike:class:`splunklib.results.ResultsReader`,whichrequiresajobto befinishedto returnanyresults,the``preview``methodreturnsanyresultsthathave beengeneratedsofar,whetherthejobisrunningornot.The returnedsearchresultsaretherawdatafromtheserver.Pass thehandlereturnedto:class:`splunklib.results.ResultsReader`togeta nice,Pythoniciteratoroverobjects,asin:: importsplunklib.clientasclient importsplunklib.resultsasresults service=client.connect(...) job=service.jobs.create("search*|head5") rr=results.ResultsReader(job.preview()) forresultinrr: ifisinstance(result,results.Message): #Diagnosticmessagesmaybereturnedintheresults print'%s:%s'%(result.type,result.message) elifisinstance(result,dict): #Normaleventsarereturnedasdicts printresult ifrr.is_preview: print"Previewofarunningsearchjob." else: print"Jobisfinished.Resultsarefinal." Thismethodmakesoneroundtriptotheserver,plusatmost twomoreif the``autologin``fieldof:func:`connect`issetto``True``. :paramquery_params:Additionalparameters(optional).Foralistofvalid parameters,see`GETsearch/jobs/{search_id}/results_preview `_ intheRESTAPIdocumentation. :typequery_params:``dict`` :return:The``InputStream``IOhandletothisjob'spreviewresults. """ query_params['segmentation']=query_params.get('segmentation','none') returnself.get("results_preview",**query_params).body開發者ID:remg427,項目名稱:misp42splunk,代碼行數:44,代碼來源:client.py 示例13:export ▲點讚4 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defexport(self,query,**params): """Runsasearchandimmediatelystartsstreamingpreviewevents. Thismethodreturnsastreaminghandletothisjob'seventsasanXML documentfromtheserver.ToparsethisstreamintousablePythonobjects, passthehandleto:class:`splunklib.results.ResultsReader`:: importsplunklib.clientasclient importsplunklib.resultsasresults service=client.connect(...) rr=results.ResultsReader(service.jobs.export("search*|head5")) forresultinrr: ifisinstance(result,results.Message): #Diagnosticmessagesmaybereturnedintheresults print'%s:%s'%(result.type,result.message) elifisinstance(result,dict): #Normaleventsarereturnedasdicts printresult assertrr.is_preview==False Runninganexportsearchismoreefficientasitstreamstheresults directlytoyou,ratherthanhavingtowritethemouttodiskandmake themavailablelater.Assoonasresultsareready,youwillreceive them. The``export``methodmakesasingleroundtriptotheserver(asopposed totwofor:meth:`create`followedby:meth:`preview`),plusatmosttwo moreifthe``autologin``fieldof:func:`connect`issetto``True``. :raises`ValueError`:Raisedforinvalidqueries. :paramquery:Thesearchquery. :typequery:``string`` :paramparams:Additionalarguments(optional).Foralistofvalid parameters,see`GETsearch/jobs/export `_ intheRESTAPIdocumentation. :typeparams:``dict`` :return:The``InputStream``IOhandletorawXMLreturnedfromtheserver. """ if"exec_mode"inparams: raiseTypeError("Cannotspecifyanexec_modetoexport.") params['segmentation']=params.get('segmentation','none') returnself.post(path_segment="export", search=query, **params).body開發者ID:remg427,項目名稱:misp42splunk,代碼行數:47,代碼來源:client.py 示例14:oneshot ▲點讚4 ▼ #需要導入模塊:fromsplunklibimportresults[as別名] #或者:fromsplunklib.resultsimportResultsReader[as別名] defoneshot(self,query,**params): """Runaoneshotsearchandreturnsastreaminghandletotheresults. The``InputStream``objectstreamsXMLfragmentsfromtheserver.To parsethisstreamintousablePythonobjects, passthehandleto:class:`splunklib.results.ResultsReader`:: importsplunklib.clientasclient importsplunklib.resultsasresults service=client.connect(...) rr=results.ResultsReader(service.jobs.oneshot("search*|head5")) forresultinrr: ifisinstance(result,results.Message): #Diagnosticmessagesmaybereturnedintheresults print'%s:%s'%(result.type,result.message) elifisinstance(result,dict): #Normaleventsarereturnedasdicts printresult assertrr.is_preview==False The``oneshot``methodmakesasingleroundtriptotheserver(asopposed totwofor:meth:`create`followedby:meth:`results`),plusatmosttwomore ifthe``autologin``fieldof:func:`connect`issetto``True``. :raisesValueError:Raisedforinvalidqueries. :paramquery:Thesearchquery. :typequery:``string`` :paramparams:Additionalarguments(optional): -"output_mode":Specifiestheoutputformatoftheresults(XML, JSON,orCSV). -"earliest_time":Specifiestheearliesttimeinthetimerangeto search.ThetimestringcanbeaUTCtime(withfractionalseconds), arelativetimespecifier(tonow),oraformattedtimestring. -"latest_time":Specifiesthelatesttimeinthetimerangeto search.ThetimestringcanbeaUTCtime(withfractionalseconds), arelativetimespecifier(tonow),oraformattedtimestring. -"rf":Specifiesoneormorefieldstoaddtothesearch. :typeparams:``dict`` :return:The``InputStream``IOhandletorawXMLreturnedfromtheserver. """ if"exec_mode"inparams: raiseTypeError("Cannotspecifyanexec_modetooneshot.") params['segmentation']=params.get('segmentation','none') returnself.post(search=query, exec_mode="oneshot", **params).body開發者ID:remg427,項目名稱:misp42splunk,代碼行數:55,代碼來源:client.py 注:本文中的splunklib.results.ResultsReader方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。



請為這篇文章評分?