本文整理汇总了Python中splunk.rest.simpleRequest函数的典型用法代码示例。如果您正苦于以下问题:Python simpleRequest函数的具体用法?Python simpleRequest怎么用?Python simpleRequest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了simpleRequest函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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.")
示例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)
示例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
示例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)
示例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
示例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'
示例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))
示例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
示例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
示例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)
示例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
示例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
示例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
示例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()})
示例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)