本文整理汇总了Python中splunk.Intersplunk.outputResults方法的典型用法代码示例。如果您正苦于以下问题:Python Intersplunk.outputResults方法的具体用法?Python Intersplunk.outputResults怎么用?Python Intersplunk.outputResults使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类splunk.Intersplunk
的用法示例。
在下文中一共展示了Intersplunk.outputResults方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def error(msg):
# for some reason the old style generateErrorResults aren't making their way into the ui.
# si.generateErrorResults("Usage: searchtxn <transaction_type> <transaction_search>. Ex: searchtxn loginsessions user=bob")
messages = {}
si.addErrorMessage(messages, msg)
si.outputResults([], messages)
exit(0)
示例2: run
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def run(results, fields):
try:
values = set()
for result in results:
field = None
for f,v in result.items():
if f not in ['count','percent']:
field = f
break
else:
continue
value = result[field]
if value.lower() == "other":
value = ' '.join(['NOT %s="%s" ' % (field, v.replace('"','\\"')) for v in values]) + ' %s=*' % field
elif value.lower() == "null":
value = 'NOT %s=*' % field
else:
values.add(value)
value = '%s="%s"' % (field, v.replace('"','\\"'))
result['_drilldown'] = value
if '_drilldown' not in fields:
fields.append('_drilldown')
si.outputResults(results, {}, fields=fields)
except Exception, e2:
stack2 = traceback.format_exc()
si.generateErrorResults("Error '%s'. %s" % (e2, stack2))
示例3: run
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def run(spantext, seriesmode, results):
try:
secsPerSpan, scalar, unit = parseSpan(spantext)
maxtime = -1
# for each results
time_data = {}
fields_seen = {}
span = None
latest = None
for result in results:
if maxtime < 0:
try:
maxtime = int(float(result['info_max_time']))
except:
maxtime = int(time.time())
maxtime -= 1 # not inclusive
if '_time' not in result:
raise Exception("Missing required _time field on data")
if span == None and '_span' in result:
span = result['_span']
mytime = int(float(result['_time']))
spansago = int((maxtime-mytime) / secsPerSpan)
new_time = mytime + (spansago * secsPerSpan)
if new_time not in time_data:
time_data[new_time] = { '_time': new_time, '_span': span }
this_row = time_data[new_time]
spanstart = maxtime - ((spansago+1)*secsPerSpan) + 1
series = seriesName(series_mode, scalar, spansago, unit, spanstart)
if spansago == 0: latest = series
acount = len(result)
for k,v in result.items():
if k not in ['_time', 'info_sid', 'info_max_time', 'info_min_time', 'info_search_time', 'info_sid', '_span']:
if k == 'count':
attr = series
else:
attr = '%s_%s' % (k, series)
this_row[attr] = result[k]
fields_seen[attr] = spansago
field_order = fields_seen.items()
field_order.sort(lambda x,y: cmp(x[1], y[1]))
field_order = [f for f,v in field_order]
field_order.insert(0,'_time')
field_order.append('_span')
results = time_data.values()
results.sort(lambda x,y: cmp(x['_time'], y['_time']))
si.outputResults(results, {}, fields=field_order)
except Exception, e2:
stack2 = traceback.format_exc()
si.generateErrorResults("Error '%s'. %s" % (e2, stack2))
示例4: main
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def main():
# get config from config file
config = ConfigParser.ConfigParser()
if os.path.exists(os.path.join('..', 'local', 'slack.conf')):
config.readfp(open(os.path.join('..', 'local', 'slack.conf')))
else:
config.readfp(open(os.path.join('..', 'default', 'slack.conf')))
# username and icon can only be set by conf
username = config.get('config', 'username')
icon = config.get('config', 'icon')
# update args if user speicify them in search
channel = kwargs.get('channel', config.get('config', 'channel'))
if not channel.startswith('#'): channel = '#' + channel
if config.get('config', 'allow_user_set_slack_url').lower() in TRUE_VALUES:
url = kwargs.get('url', config.get('config', 'url'))
else:
url = config.get('config', 'url')
# no url specified, dont procceed.
if not url:
raise Exception("Not slack url specified!")
# read search results
results = sis.readResults(None, None, True)
https_proxy = config.get('config', 'proxy')
proxyDict = {
"https" : https_proxy
}
# prepare data to be sent to slack
data = {
'text': get_pretty_table(results),
'username': username,
'channel': channel,
'icon_url': icon,
'mrkdwn': True,
}
if https_proxy != "":
# send data to slack.
r = requests.post(url, data=json.dumps(data), proxies=proxyDict)
else:
r = requests.post(url, data=json.dumps(data))
if r.status_code == 200:
sis.outputResults(results)
else:
err_msg = ("Error sending results to slack, reason: {r}, {t}".format(
r=r.reason, t=r.text))
sis.generateErrorResults(err_msg)
示例5: main
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def main():
# get config from config file
config = ConfigParser.ConfigParser()
config.readfp(open(os.path.join('..', 'default', 'hipchat.conf')))
# update args if user speicify them in search
room = kwargs.get('room', config.get('default', 'room'))
color = kwargs.get('color', config.get('default', 'color'))
notify = kwargs.get('notify', config.get('default', 'notify'))
msg_fmt = kwargs.get('message_format',
config.get('default', 'message_format'))
if config.get('default', 'allow_users_set_base_url').lower() in TRUE_VALUES:
base_url = kwargs.get('base_url', config.get('default', 'base_url'))
else:
base_url = config.get('default', 'base_url')
# check if auth token is set properly
try:
auth_token = {"auth_token": config.get(room, 'auth_token')}
except ConfigParser.NoSectionError as e:
raise Exception("Room not set, please set the room stanza")
except ConfigParser.NoOptionError as e:
raise Exception("Auth token not set, please set auth token for room")
# construct url
url = base_url + "{s}{r}/notification".format(
s='' if base_url.endswith('/') else '/', r=room)
# read search results
results = sis.readResults(None, None, True)
# prepare data to be sent
data = {
'message': get_pretty_table(results, msg_fmt),
'message_format': msg_fmt,
'color': color,
'notify': notify.lower() in TRUE_VALUES
}
# send data
headers = {'Content-type': 'application/json'}
r = requests.post(url,
data=json.dumps(data),
params=auth_token,
headers=headers)
if r.status_code == 204:
sis.outputResults(results)
else:
err_msg = ("Error sending results to slack, reason: {r}, {t}".format(
r=r.reason, t=r.text))
sis.generateErrorResults(err_msg)
示例6: run
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def run(messages, count, mapping):
results = si.readResults(None, None, True)
ORS = []
seenValues = set() # dedup rows
for i, result in enumerate(results):
if count > 0 and i >= count:
break
ANDS = []
for j, (renamed, attr) in enumerate(mapping):
val = str(result.get(attr,''))
if renamed == None or renamed == '':
if val != '':
ANDS.append(val)
else:
ANDS.append('%s="%s"' % (renamed, val))
andstr = str(ANDS)
if len(ANDS) > 0 and andstr not in seenValues:
ORS.append(ANDS)
seenValues.add(andstr)
output = ""
if len(ORS) > 1:
output += "("
for i, OR in enumerate(ORS):
if i > 0:
output += ") OR ("
for j, AND in enumerate(OR):
if j > 0:
output += " " #" AND "
output += AND
if len(ORS) > 1:
output += ")"
si.outputResults([{'search': output}], messages)
示例7: int
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
if sys.argv[1] == 'filters':
filters = client.service.getFavouriteFilters(auth)
keys = (('author', None), ('id', None), ('name', None))
results = []
for filter in filters:
row = jiracommon.flatten(filter, keys)
logger.info(time.time())
row['host'] = hostname
row['source'] = "jira_soap"
row['sourcetype'] = "jira_filters"
row['_time'] = int(time.time())
results.append(row)
isp.outputResults(results)
sys.exit(0)
elif sys.argv[1] == 'issues':
filter_id = sys.argv[-1]
issues = client.service.getIssuesFromFilter(auth, filter_id)
# TODO this 1000 issue max isn't working as expected - if there are more than 1000 results, no results are returned
elif sys.argv[1] == 'search':
search = sys.argv[-1]
issues = (client.service.getIssuesFromTextSearch(auth, search, 1000) )
elif sys.argv[1] == 'jqlsearch':
jql = sys.argv[-1]
issues = (client.service.getIssuesFromJqlSearch(auth, jql, 1000) )
else:
logger.fatal('invalid command')
sys.exit(1)
示例8: Exception
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
logger.debug('Ending Output')
#if not proc_err == '':
# raise Exception("prestrace returned something in stderr: '%s'" % proc_err)
lines = proc_err.split("\n")
results = []
re_time = re.compile(r'^(\d+\.\d\d\d)\d+\s+(\w+).*\<(\d+\.\d+)\>')
for line in lines:
if line != '':
res = {}
res['_raw'] = line
m = re_time.match(line)
if m:
res['_time'] = m.group(1)
res['call'] = m.group(2)
res['duration'] = m.group(3)
results.append(res)
logger.debug(pprint.pformat(results))
si.outputResults(results, fields=['_raw'])
logger.debug("exited __main__")
except Exception, e:
si.generateErrorResults(e)
示例9: str
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
results = []
now = str(int(time.mktime(time.gmtime())))
start = 0
# google rest api returns very few results, get many pages of a small number of results
for loop in range(0, 20):
try:
# Define the query to pass to Google Search API
query = urllib.urlencode({'q' : search, 'start' : start})
# Fetch the results and convert to JSON
search_results = urllib2.urlopen(GOOGLE_REST_URL % query)
data = json.loads(search_results.read())
hits = data['responseData']['results']
for h in hits:
raw = stripCommonHTML(sax.unescape(h['content']))
title = stripCommonHTML(h['titleNoFormatting'])
url = h['unescapedUrl']
results.append({'title' : title , 'url' : url , '_time' : now, 'description' : raw, '_raw' : title + "... " + raw})
start += len(hits)
if len(results) > maxresults:
break
except:
break
si.outputResults(results[:maxresults])
except Exception, e:
import traceback
stack = traceback.format_exc()
si.generateErrorResults("Error '%s'. %s" % (e, stack))
示例10: len
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
output += " " #" AND "
output += AND
if len(ORS) > 1:
output += ")"
si.outputResults([{'search': output}], messages)
if __name__ == '__main__':
messages = {}
try:
(isgetinfo, sys.argv) = si.isGetInfo(sys.argv)
argtext = ' '.join(sys.argv[1:])
count, mapping = parseArgs(argtext)
if isgetinfo:
reqsop = True
preop = "head %s" % count
fields = [field for alias, field in mapping]
if len(fields) > 0:
preop += " | fields %s" % ', '.join(fields)
si.outputInfo(False, False, False, reqsop, preop) # calls sys.exit()
run(messages, count, mapping)
except Exception, e:
import traceback
stack = traceback.format_exc()
si.addErrorMessage(messages, "%s. Traceback: %s" % (e, stack.replace('\n','\\n')))
si.outputResults([], messages)
示例11: len
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
gpath = gpath.replace('\]', ']')
# find all files matching
complete_path = os.path.expanduser(
os.path.expandvars(gpath))
glob_matches = glob.glob(complete_path)
logger.error("complete path: %s" % complete_path)
logger.error("glob matches: %s" % glob_matches)
if len(glob_matches)==0:
logger.error("No file matching %s" % complete_path)
raise Exception("No files matching %s." % complete_path)
for pfile in glob_matches:
logger.error("parsing file: %s" % pfile)
results += parse_pstack_file(pfile, separator, fileorderindex)
#return results
return results
# noinspection PyUnreachableCode
if __name__ == '__main__':
try:
si.outputResults(parse_pstacks(), messages, fields)
except Exception, e:
import traceback
stack = traceback.format_exc()
si.generateErrorResults("Following error occurred while parsing pstack: '%s'." % (e))
logger.error("%s. %s" % (e, stack))
示例12: entityToResult
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
# e.g., '/data/inputs/monitor'
entity = keywords[0]
logger.info("Entity: %s Args: %s" % (entity, args))
results = [] # we don't care about incoming results
try:
entitys = en.getEntities(entity, sessionKey=sessionKey, owner=owner, namespace=namespace, count=-1)
for name, entity in entitys.items():
try:
myapp = entity["eai:acl"]["app"]
if namespace != None and myapp != namespace:
continue
except:
continue # if no eai:acl/app, filter out
result = entityToResult(name, entity)
results.append(result)
except splunk.ResourceNotFound, e2:
pass
si.outputResults(results, messages)
except Exception, e:
import traceback
stack = traceback.format_exc()
logger.error(str(e) + ". Traceback: " + str(stack))
si.generateErrorResults(str(e))
if __name__ == "__main__":
execute()
示例13: dict
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
if __name__ == '__main__':
stdin = None
if not os.isatty(0):
stdin = sys.stdin
settings = dict()
records = si.readResults(settings = settings, has_header = True)
sessionKey = settings['sessionKey']
for i in range(1, len(sys.argv)):
logger.debug("query = %s" % sys.argv[i])
func = parse_func(sys.argv[i])
logger.debug("func arguments = %s" % func.arguments)
for rec in records:
# it is good pratice to always pass sessionKey to functions
rf = run_func (func, sessionKey=sessionKey, **rec)
if isinstance(rf, dict):
rec.update(rf)
else:
nm = func.alias if func.alias!=None else func.name
rec.update({nm:rf})
si.outputResults(records)
示例14: _do_handle
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
def _do_handle(self):
self._logger.info("Start of %s", self._get_log_file())
result = self._handle_events()
si.outputResults(result)
self._logger.info("End of %s", self._get_log_file())
示例15: type
# 需要导入模块: from splunk import Intersplunk [as 别名]
# 或者: from splunk.Intersplunk import outputResults [as 别名]
stdinArgs = urllib.unquote(stdinArgs).decode('utf8')
match = re.search(r'<authToken>([^<]+)</authToken>', stdinArgs)
sessionKey = match.group(1)
incident_id = sys.argv[1]
query = {}
query['incident_id'] = incident_id
uri = '/servicesNS/nobody/alert_manager/storage/collections/data/incident_results?query=%s' % urllib.quote(json.dumps(query))
serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey)
data = json.loads(serverContent)
#sys.stderr.write("data: %s" % data)
field_list = None
results = []
for result in data:
if "field_list" in result:
field_list = result["field_list"]
for line in result["fields"]:
if type(field_list) is list:
ordered_line = collections.OrderedDict()
for field in field_list:
ordered_line[field] = line[field]
results.append(ordered_line)
else:
results.append(line)
intersplunk.outputResults(results)