• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python rest.simpleRequest函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中splunk.rest.simpleRequest函数的典型用法代码示例。如果您正苦于以下问题:Python simpleRequest函数的具体用法?Python simpleRequest怎么用?Python simpleRequest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了simpleRequest函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: autoPreviousResolve

def autoPreviousResolve(alert, job_id):
    # Auto Previous resolve

    log.info("auto_previous_resolve is active for alert %s, searching for incidents to resolve..." % alert)
    query = '{  "alert": "'+ alert +'", "$or": [ { "status": "auto_assigned" } , { "status": "new" } ], "job_id": { "$ne": "'+ job_id +'"} }'
    log.debug("Filter for auto_previous_resolve: %s" % query)
    uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incidents?query=%s' % urllib.quote(query)
    serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
    incidents = json.loads(serverContent)
    if len(incidents):
        log.info("Got %s incidents to auto-resolve" % len(incidents))
        for incident in incidents:
            log.info("Auto-resolving incident with key=%s" % incident['_key'])

            previous_status = incident["status"]
            previous_job_id = incident["job_id"]
            previous_incident_id = incident["incident_id"]

            incident['status'] = 'auto_previous_resolved'
            uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incidents/%s' % incident['_key']
            incident = json.dumps(incident)
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=incident)

            now = datetime.datetime.now().isoformat()
            event_id = hashlib.md5(job_id + now).hexdigest()
            log.debug("event_id=%s now=%s incident=%s" % (event_id, now, incident))


            event = 'time=%s severity=INFO origin="alert_handler" event_id="%s" user="splunk-system-user" action="auto_previous_resolve" previous_status="%s" status="auto_previous_resolved" incident_id="%s" job_id="%s"' % (now, event_id, previous_status, previous_incident_id, previous_job_id)
            log.debug("Resolve event will be: %s" % event)
            input.submit(event, hostname = socket.gethostname(), sourcetype = 'incident_change', source = 'alert_handler.py', index = config['index'])
    else:
        log.info("No incidents with matching criteria for auto_previous_resolve found.")
开发者ID:rfsp,项目名称:alert_manager,代码行数:33,代码来源:alert_handler.py


示例2: create_lookup_table

def create_lookup_table(filename, lookup_file, namespace, owner, key):
    '''
    Create a new lookup file.

    @param filename: The full path to the replacement lookup table file.
    @param lookup_file: The lookup FILE name (NOT the stanza name)
    @param namespace: A Splunk namespace to limit the search to.
    @param owner: A Splunk user.
    @param key: A Splunk session key.
    
    @return: Boolean success status.
    
    WARNING: "owner" should be "nobody" to update
    a public lookup table file; otherwise the file will be replicated
    only for the admin user.
    '''
    
    # Create the temporary location path
    lookup_tmp = make_splunkhome_path(['var', 'run', 'splunk', 'lookup_tmp'])
    destination_lookup_full_path = os.path.join(lookup_tmp, lookup_file)

    # Copy the file to the temporary location
    shutil.move(filename, destination_lookup_full_path)

    # CReate the URL for the REST call
    url = '/servicesNS/%s/%s/data/lookup-table-files' % (owner, namespace)
    postargs = {
        'output_mode': 'json',
        'eai:data': str(destination_lookup_full_path),
        'name': lookup_file
    }

    # Perform the call
    rest.simpleRequest(
         url, postargs=postargs, sessionKey=key, raiseAllErrors=True)
开发者ID:LukeMurphey,项目名称:lookup-editor,代码行数:35,代码来源:lookupfiles.py


示例3: isRestartRequired

 def isRestartRequired(self):
     """Query the messages endpoint to determine whether a restart is currently required"""
     try:
         rest.simpleRequest('/messages/restart_required', sessionKey=cherrypy.session['sessionKey'])
         return True
     except splunk.ResourceNotFound:
         return False
开发者ID:MobileWebApps,项目名称:splunk-search-tools-app,代码行数:7,代码来源:appinstall.py


示例4: __init__

	def __init__(self, sessionKey, incident_id):
		self.sessionKey = sessionKey

		query = {}
		query['incident_id'] = incident_id

		uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incidents?query=%s' % urllib.quote(json.dumps(query))
		serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
		incident = json.loads(serverContent)
		incident = incident[0]

		query_incident_settings = {}
		query_incident_settings['alert'] = incident["alert"]
		uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incident_settings?query=%s' % urllib.quote(json.dumps(query_incident_settings))
		serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
		incident_settings = json.loads(serverContent)
		if len(incident_settings) > 0:
			incident_settings = incident_settings[0]

		uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incident_results?query=%s' % urllib.quote(json.dumps(query))
		serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
		results = json.loads(serverContent)
		if len(results) > 0:
			results = results[0]

		uri = '/services/server/info?output_mode=json'
		serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
		server_info = json.loads(serverContent)
		if len(server_info) > 0:
			server_info = server_info["entry"][0]["content"]

		self.setContext(incident, incident_settings, results, server_info)
开发者ID:thawkson,项目名称:alert_manager,代码行数:32,代码来源:IncidentContext.py


示例5: getRestData

def getRestData(uri, sessionKey, data = None, output_mode = 'json'):
    try:
        if data == None:
            if output_mode == 'default':
                serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
            else:
                serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, getargs={'output_mode': 'json'})
        else:
            if output_mode == 'default':
                serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=data)
            else:
                serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=data, getargs={'output_mode': 'json'})
    except:
        log.info("An error occurred or no data was returned from the server query.")
        serverContent = None

    #log.debug("serverResponse: %s" % serverResponse)
    #log.debug("serverContent: %s" % serverContent)
    try:
        returnData = json.loads(serverContent)
    except:
        log.info("An error occurred or no data was returned from the server query.")
        returnData = []

    return returnData
开发者ID:simcen,项目名称:alert_manager,代码行数:25,代码来源:alert_manager.py


示例6: save_risks

    def save_risks(self, contents, **kwargs):

        logger.info("Saving risks...")

        user = cherrypy.session['user']['name']
        sessionKey = cherrypy.session.get('sessionKey')
        splunk.setDefault('sessionKey', sessionKey)
        

        config = {}
        config['index'] = 'risks'
        
        restconfig = entity.getEntities('configs/risk_manager', count=-1, sessionKey=sessionKey)
        if len(restconfig) > 0:
            if 'index' in restconfig['settings']:
                config['index'] = restconfig['settings']['index']

        logger.debug("Global settings: %s" % config)

        # Parse the JSON
        parsed_contents = json.loads(contents)
        logger.debug("Contents: %s" % contents)

        for entry in parsed_contents:
            if '_key' in entry and entry['_key'] != None:

                uri = '/servicesNS/nobody/risk_manager/storage/collections/data/risks/' + entry['_key']
                
                # Get current risk
                serverResponse, risk = rest.simpleRequest(uri, sessionKey=sessionKey)
                logger.debug("Current risk: %s" % risk)
                risk = json.loads(risk)

                # Update risk if score has changed
                if int(risk['risk_score']) != int(entry['risk_score']):
                    logger.info("Updating risk_object_type=%s risk_object=%s to score=%s." % (entry['risk_object_type'], entry['risk_object'], entry['risk_score']))
                    del entry['_key']
                    if 'risk_id' in risk:
                        entry['risk_id'] = risk['risk_id']
                    else:
                        entry['risk_id'] = str(uuid.uuid4())
                        risk['risk_id'] = entry['risk_id']
                    entryStr = json.dumps(entry)

                    serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=entryStr)
                    logger.debug("Updated entry. serverResponse was ok")

                    now = datetime.datetime.now().isoformat()
                    event = 'time="%s" risk_id="%s" action="update_risk_score" alert="Risk Score Tuner" user="%s" risk_object_type="%s" risk_object="%s" risk_score="%s" previous_risk_score="%s"' % (now, risk['risk_id'], user, entry['risk_object_type'], entry['risk_object'], entry['risk_score'], risk['risk_score'])
                    logger.debug("Event will be: %s" % event)
                    input.submit(event, hostname = socket.gethostname(), sourcetype = 'risk_scoring', source = 'helpers.py', index = config['index'])
                else:
                    logger.info("Won't update risk_object_type=%s risk_object=%s, since score didn't change." % (entry['risk_object_type'], entry['risk_object']))

        return 'Done'
开发者ID:jpressnell,项目名称:risk_manager,代码行数:55,代码来源:helpers.py


示例7: assignIncident

def assignIncident(incident_key, incident_id, owner):
    uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incidents/%s' % incident_key
    serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
    
    incident = json.loads(serverContent)
    incident["owner"] = owner
    incident["status"] = "auto_assigned"
    if "_user" in incident:
        del(incident["_user"])
    if "_key" in incident:
        del(incident["_key"])
    serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=json.dumps(incident))

    log.info("Incident %s assigned to %s" % (incident_id, owner))
开发者ID:IceEyz,项目名称:alert_manager,代码行数:14,代码来源:alert_handler.py


示例8: _reload

 def _reload(self):
     path = '/'.join([self.id.rsplit('/', 1)[0], '_reload'])
     response, content = rest.simpleRequest(path,
                              method='POST')
     if response.status == 200:
         return True
     return False
开发者ID:amoswood,项目名称:puppet-splunk,代码行数:7,代码来源:input.py


示例9: parseSearchToXML

def parseSearchToXML(search, hostPath=None, sessionKey=None, parseOnly='t', namespace=None, owner=None):
    """
        Given a valid search string, return the XML from the splunk parsing endpoint that
        represents the search.
    """

    if search == None or len(search) == 0:
        return None
    
    if not owner: owner = auth.getCurrentUser()['name']
    
    uri = entity.buildEndpoint('/search/parser', namespace=namespace, owner=owner)
    if hostPath:
        uri = splunk.mergeHostPath(hostPath) + uri

    args = {
        'q'             : search,
        'parse_only'    : parseOnly
    }

    serverResponse, serverContent = rest.simpleRequest(uri, getargs=args, sessionKey=sessionKey)
    #print "SERVERCONTENT:", serverContent
    # normal messages from splunkd are propogated via SplunkdException;
    if 400 <= serverResponse.status < 500:
        root = et.fromstring(serverContent)
        extractedMessages = rest.extractMessages(root)
        for msg in extractedMessages:
            raise splunk.SearchException, msg['text']

    return serverContent
开发者ID:DRArpitha,项目名称:splunk,代码行数:30,代码来源:Parser.py


示例10: test_ping_handler

 def test_ping_handler(self):
     """
     Make sure the handler is onlne.
     """
     response, content = simpleRequest("/services/data/lookup_backup/ping",
                                       sessionKey=self.get_session_key())
     self.assertEqual(response.status, 200)
开发者ID:LukeMurphey,项目名称:lookup-editor,代码行数:7,代码来源:unit.py


示例11: createContext

def createContext(incident, incident_settings, results):
    context = { }
    try:
        uri = '/services/server/info?output_mode=json'
        serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
        server_info = json.loads(serverContent)
        if len(server_info) > 0:
            server_info = server_info["entry"][0]["content"]

        context.update({ "alert_time" : incident["alert_time"] })
        context.update({ "owner" : incident["owner"] })
        context.update({ "name" : incident["alert"] })
        context.update({ "alert" : { "impact": incident["impact"], "urgency": incident["urgency"], "priority": incident["priority"], "expires": incident["ttl"] } })
        context.update({ "app" : incident["app"] })
        context.update({ "category" : incident_settings['category'] })
        context.update({ "subcategory" : incident_settings['subcategory'] })
        context.update({ "tags" : incident_settings['tags'] })
        context.update({ "results_link" : "http://"+server_info["host_fqdn"] + ":8000/app/" + incident["app"] + "/@go?sid=" + incident["job_id"] })
        context.update({ "view_link" : "http://"+server_info["host_fqdn"] + ":8000/app/" + incident["app"] + "/alert?s=" + urllib.quote("/servicesNS/nobody/"+incident["app"]+"/saved/searches/" + incident["alert"] ) })
        context.update({ "server" : { "version": server_info["version"], "build": server_info["build"], "serverName": server_info["serverName"] } })

        if "fields" in results:
            result_context = { "result" : results["fields"] }
            context.update(result_context)  

    except Exception as e:
        log.error("Unexpected Error: %s" % (traceback.format_exc()))

    return context                 
开发者ID:IceEyz,项目名称:alert_manager,代码行数:29,代码来源:alert_handler.py


示例12: index

    def index(self, **params):
        ssId = params.get('s')

        #no ssId
        if not ssId:
            raise cherrypy.HTTPError(400, _('Must specify a savedsearch id.'))

        #fetch saved search
        responseHeaders, responseBody = simpleRequest(ssId, method='GET', getargs={'output_mode':'json'}, sessionKey=cherrypy.session['sessionKey'])
        savedSearchJSON = json.loads(responseBody)
        app = savedSearchJSON['entry'][0]['content'].get("request.ui_dispatch_app") or\
            savedSearchJSON['entry'][0]['acl'].get("app") or 'search'

        #scheduled view
        if '_ScheduledView__' in ssId:
            #redirect to dashboard page
            name = savedSearchJSON['entry'][0]['name']
            name = string.replace(name, '_ScheduledView__', '', 1)
            self.redirect_to_url(['app', app, name], _qs={'dialog': 'schedulePDF'})

        if savedSearchJSONIsAlert(savedSearchJSON):
            #if alert route to  :app/alert?s=ssId
            self.redirect_to_url(['app', app, 'alert'], _qs={'s': ssId, 'dialog': 'actions'})
        #report - :app/report?s=ssId
        self.redirect_to_url(['app', app, 'report'], _qs={'s': ssId, 'dialog': 'schedule'})
        return
开发者ID:MobileWebApps,项目名称:splunk-search-tools-app,代码行数:26,代码来源:savedsearchredirect.py


示例13: toggle_search

    def toggle_search(self, search_name, action, **kwargs):
        user = cherrypy.session['user']['name']
        sessionKey = cherrypy.session.get('sessionKey')

        if action == 'enable':
            uri = '/servicesNS/nobody/SA-alert_manager_demo/saved/searches/%s/enable' % search_name
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, method='POST')
            logger.info("Enabled search=%s", search_name)   

            return 'Alert %s has been enabled' % search_name
        else:
            uri = '/servicesNS/nobody/SA-alert_manager_demo/saved/searches/%s/disable' % search_name
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, method='POST')
            logger.info("Disabled search=%s", search_name)   

            return 'Alert %s has been disabled' % search_name
开发者ID:c0ns0le,项目名称:SA-alert_manager_demo,代码行数:16,代码来源:demo_data.py


示例14: install

    def install(self, appid, state, install=None, **kw):
        """
        Start the app download and installation processs
        """
        if not isinstance(state, StateDict):
            state = StateDict.unserialize(state)
        sbSessionKey = self.getSBSessionKey()
        if not sbSessionKey:
            logger.warn("Attempted install of app '%s' with sbSessionKey unset" % appid)
            return self.redirect_to_url(['/manager/appinstall/', appid], _qs={'error': _('SplunkApps login failed'), 'state': state.serialize()}) 

        # don't hold the session lock through network I/O
        cherrypy.session.release_lock()

        # attempt to actually install the app
        url = 'apps/remote/entriesbyid/%s' % appid
        requestArgs = {'action': 'install', 'auth': urllib.quote(sbSessionKey)}
        try:
            logger.info("Installing app %s" % appid)
            response, content = rest.simpleRequest(url, postargs=requestArgs, sessionKey=cherrypy.session['sessionKey'], timeout=APP_INSTALL_TIMEOUT)
        except splunk.AuthenticationFailed:
            # login expired
            return self.redirect_to_url(['/manager/appinstall', appid], _qs={'error': _('SplunkApps login timed out'), 'state': state.serialize()})
        except Exception, e:
            logger.exception(e)
            if e.statusCode == 403:
                return self.render_admin_template('/admin/appinstall/sb-login.html', {
                    'appid': appid,
                    'breadcrumbs': state['breadcrumbs'],
                    'error': _('SplunkApps login timed out'),
                    'state': state,
                    'next': install
                })
            else:
                return self.redirect_to_url(['/manager/appinstall', appid], _qs={'error': _('An error occurred while downloading the app: %s') % str(e), 'state': state.serialize()})
开发者ID:MobileWebApps,项目名称:splunk-search-tools-app,代码行数:35,代码来源:appinstall.py


示例15: processAppUpload

    def processAppUpload(self, f, force):
        """
        Process a file uploaded from the upload page
        """
        if not (isinstance(f, cgi.FieldStorage) and f.file):
            raise SBFileUploadException(_("No file was uploaded."))

        # Copy uploaded data to a named temporary file
        fd, tmpPath = tempfile.mkstemp()
        tfile = os.fdopen(fd, "w+")
        shutil.copyfileobj(f.file, tfile)
        tfile.flush() # leave the file open, but flush so it's all committed to disk

        try:
            args = { 'name': tmpPath, 'filename' : 1 }
            if force: 
                args['update'] = 1
            response, content = rest.simpleRequest('apps/local', postargs=args, sessionKey=cherrypy.session['sessionKey'])
            if response.status in (200, 201):
                atomFeed = rest.format.parseFeedDocument(content)
                return atomFeed[0].toPrimitive()['name']
            elif response.status == 409:
                raise SBFileUploadException(_("App with this name already exists."))
            raise SBFileUploadException(_("There was an error processing the upload."))
        except splunk.AuthorizationFailed:
            raise SBFileUploadException(_("Client is not authorized to upload apps."))
        finally:
			shutil.rmtree(tmpPath, True)
开发者ID:MobileWebApps,项目名称:splunk-search-tools-app,代码行数:28,代码来源:appinstall.py


示例16: update

 def update(self, appid, state, update=None, **kw):
     """
     Attempt to download and install an app update from Splunkbase
     """
     if not isinstance(state, StateDict):
         state = StateDict.unserialize(state)
     sbSessionKey = self.getSBSessionKey()
     if not sbSessionKey:
         # login required
         return self.render_admin_template('/admin/appinstall/sb-login.html', {
             'appid': appid,
             'breadcrumbs': state['breadcrumbs'],
             'state': state,
             'next': 'update'
         })
     url = 'apps/local/%s/update' % appid
     requestArgs = {
         'auth': urllib.quote(sbSessionKey),
         'implicit_id_required' : state.get('implicit_id_required')
     }
     try:
         logger.info("Updating app %s" % appid)
         response, content = rest.simpleRequest(url, postargs=requestArgs, sessionKey=cherrypy.session['sessionKey'])
     except splunk.AuthenticationFailed:
         # login expired
         return self.redirect_to_url(['/manager/appinstall', appid], _qs={'error': _('Splunkbase login timed out'), 'state': state.serialize()})
     except Exception, e:
         return self.redirect_to_url(['/manager/appinstall', appid], _qs={'error': _('An error occurred while downloading the app: %s') % str(e), 'state': state.serialize()})
开发者ID:DRArpitha,项目名称:splunk,代码行数:28,代码来源:appinstall.py


示例17: getRestData

def getRestData(uri, sessionKey, data = None, output_mode = 'json'):
    if data == None:
        if output_mode == 'default':
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
        else:
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, getargs={'output_mode': 'json'})
    else:
        if output_mode == 'default':
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=data)
        else:
            serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, jsonargs=data, getargs={'output_mode': 'json'})

    #log.debug("serverResponse: %s" % serverResponse)
    #log.debug("serverContent: %s" % serverContent)
    returnData = json.loads(serverContent)
    return returnData
开发者ID:IceEyz,项目名称:alert_manager,代码行数:16,代码来源:alert_manager.py


示例18: call_peer

def call_peer(remote_host, remote_user, local_host, local_user, ts, nonce, signature):
    ''' make remote REST call to retreive foreign sessionKey '''
    postargs = {
        'name': '_create',
        'userid': local_user,
        'peername': local_host,
        'username': remote_user,
        'ts': ts,
        'nonce': nonce,
        'sig': signature
    }
    
    resp, cont = rest.simpleRequest(remote_host + REMOTE_ENDPOINT, postargs=postargs)

    if resp.status not in [200, 201]:
        logger.error('unable to get session key from remote peer %s' % remote_host)
        
        return None

    try:
        atomEntry = rest.format.parseFeedDocument(cont)
        ret = atomEntry.toPrimitive()[remote_user][remote_user]
        return ret
    except Exception, ex:
        logger.error('unable to parse response from remote peer %s' % remote_host)
        logger.exception(ex) 
        return None
开发者ID:parth88,项目名称:GitHub,代码行数:27,代码来源:remote_auth.py


示例19: reload

 def reload( session_key=None ):
     path = SplunkLookupTableFile.resource + "/" + '_reload'
     
     response, content = rest.simpleRequest(path, method='GET', sessionKey=session_key)
     if response.status == 200:
         return True
     
     return False
开发者ID:LukeMurphey,项目名称:lookup-editor,代码行数:8,代码来源:lookupfiles.py


示例20: validate_time

 def validate_time(self, time):
     try:
         serverResponse, serverContent = rest.simpleRequest('/services/search/timeparser', getargs={'time': time, 'output_mode':'json'}, rawResult=True)
     except Exception:
         return False
     if serverResponse and serverResponse.status == 200:
         return True
     return False
开发者ID:MobileWebApps,项目名称:splunk-search-tools-app,代码行数:8,代码来源:dashboard_panel.py



注:本文中的splunk.rest.simpleRequest函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python binding.connect函数代码示例发布时间:2022-05-27
下一篇:
Python saved_search.SavedSearch类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap