forked from splunk/splunk-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
executable file
·111 lines (91 loc) · 3.41 KB
/
search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env python
#
# Copyright 2011 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""A command line utility for executing Splunk searches."""
from pprint import pprint
import sys
from time import sleep
from splunk.binding import HTTPError
import splunk.client as client
from utils import *
FLAGS_TOOL = [ "verbose" ]
FLAGS_CREATE = [
"earliest_time", "latest_time", "now", "time_format",
"exec_mode", "search_mode", "rt_blocking", "rt_queue_size",
"rt_maxblocksecs", "rt_indexfilter", "id", "status_buckets",
"max_count", "max_time", "timeout", "auto_finalize_ec", "enable_lookups",
"reload_macros", "reduce_freq", "spawn_process", "required_field_list",
"rf", "auto_cancel", "auto_pause",
]
FLAGS_RESULTS = [
"offset", "count", "search", "field_list", "f", "output_mode"
]
def cmdline(argv, flags, **kwargs):
"""A cmdopts wrapper that takes a list of flags and builds the
corresponding cmdopts rules to match those flags."""
rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags])
return parse(argv, rules, ".splunkrc", **kwargs)
def main(argv):
usage = 'usage: %prog [options] "search"'
flags = []
flags.extend(FLAGS_TOOL)
flags.extend(FLAGS_CREATE)
flags.extend(FLAGS_RESULTS)
opts = cmdline(argv, flags, usage=usage)
if len(opts.args) != 1:
error("Search expression required", 2)
search = opts.args[0]
verbose = opts.kwargs.get("verbose", 0)
kwargs_splunk = dslice(opts.kwargs, FLAGS_SPLUNK)
kwargs_create = dslice(opts.kwargs, FLAGS_CREATE)
kwargs_results = dslice(opts.kwargs, FLAGS_RESULTS)
service = client.connect(**kwargs_splunk)
try:
service.parse(search, parse_only=True)
except HTTPError as e:
cmdopts.error("query '%s' is invalid:\n\t%s" % (search, e.message), 2)
return
job = service.jobs.create(search, **kwargs_create)
while True:
stats = job.read(
'isDone',
'doneProgress',
'scanCount',
'eventCount',
'resultCount')
progress = float(stats['doneProgress'])*100
scanned = int(stats['scanCount'])
matched = int(stats['eventCount'])
results = int(stats['resultCount'])
if verbose > 0:
status = ("\r%03.1f%% | %d scanned | %d matched | %d results" % (
progress, scanned, matched, results))
sys.stdout.write(status)
sys.stdout.flush()
if stats['isDone'] == '1':
if verbose > 0: sys.stdout.write('\n')
break
sleep(2)
if not kwargs_results.has_key('count'): kwargs_results['count'] = 0
results = job.results(**kwargs_results)
while True:
content = results.read(1024)
if len(content) == 0: break
sys.stdout.write(content)
sys.stdout.flush()
sys.stdout.write('\n')
job.cancel()
if __name__ == "__main__":
main(sys.argv[1:])