Exemple #1
0
def main():
    """Main program."""

    usage = "usage: %prog [options] <command> [<args>]"

    argv = sys.argv[1:]

    command = None
    commands = ['create', 'delete', 'list']

    # parse args, connect and setup 
    opts = parse(argv, {}, ".splunkrc", usage=usage)
    service = connect(**opts.kwargs)
    program = Program(service)

    if len(opts.args) == 0:
        # no args means list
        command = "list"
    elif opts.args[0] in commands:
        # args and the first in our list of commands, extract 
        # command and remove from regular args
        command = opts.args[0]
        opts.args.remove(command)
    else:
        # first one not in our list, default to list
        command = "list"

    program.run(command, opts)
Exemple #2
0
def main():
    usage = "usage: follow.py <search>"
    opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)

    if len(opts.args) != 1:
        utils.error("Search expression required", 2)
    search = opts.args[0]

    service = client.connect(**opts.kwargs)

    job = service.jobs.create(search, earliest_time="rt", latest_time="rt", search_mode="realtime")

    # Wait for the job to transition out of QUEUED and PARSING so that
    # we can if its a transforming search, or not.
    while True:
        entity = job.read()
        state = entity["dispatchState"]
        if state not in ["QUEUED", "PARSING"]:
            break
        time.sleep(2)  # Wait

    if entity["reportSearch"] is not None:  # Is it a transforming search?
        count = lambda: int(job["numPreviews"])
        items = lambda _: job.preview()
    else:
        count = lambda: int(job["eventCount"])
        items = lambda offset: job.events(offset=offset)

    try:
        follow(job, count, items)
    except KeyboardInterrupt:
        print "\nInterrupted."
    finally:
        job.cancel()
Exemple #3
0
def main():
    usage = "usage: %prog <search>"
    opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)

    if len(opts.args) != 1:
        utils.error("Search expression required", 2)
    search = opts.args[0]

    service = connect(**opts.kwargs)

    try:
        result = service.get(
            "search/jobs/export",
            search=search,
            earliest_time="rt", 
            latest_time="rt", 
            search_mode="realtime")

        reader = results.ResultsReader(result.body)
        while True:
            kind = reader.read()
            if kind == None: break
            if kind == results.RESULT:
                event = reader.value
                pprint(event)

    except KeyboardInterrupt:
        print "\nInterrupted."
Exemple #4
0
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()
Exemple #5
0
def main():
    usage = "usage: oneshot.py <search>"
    opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)
    opts.kwargs["namespace"] = "*:*" # Override namespace

    if len(opts.args) != 1:
        utils.error("Search expression required", 2)
    search = opts.args[0]

    service = connect(**opts.kwargs)
    socket.setdefaulttimeout(None)
    response = service.jobs.create(search, exec_mode="oneshot")

    pretty(response)
def main():
    usage = "usage: %prog [options] <command> [<args>]"

    argv = sys.argv[1:]
    if len(argv) == 0:
        print "must supply an index name"
        sys.exit(1)

    opts = parse(argv, RULES, ".splunkrc", usage=usage)
    service = connect(**opts.kwargs)

    if opts.kwargs['ingest'] not in INGEST_TYPE:
        print "ingest type must be in set %s" % INGEST_TYPE
        sys.exit(1)

    feed_index(service, opts)
Exemple #7
0
def main():
    usage = "usage: %prog [options] <command> [<args>]"

    argv = sys.argv[1:]

    # Locate the command
    index = next((i for i, v in enumerate(argv) if not v.startswith('-')), -1)

    if index == -1: # No command
        options = argv
        command = ["list"]
    else:
        options = argv[:index]
        command = argv[index:]

    opts = parse(options, {}, ".splunkrc", usage=usage, epilog=HELP_EPILOG)
    service = connect(**opts.kwargs)
    program = Program(service)
    program.run(command)
from pprint import pprint
from StringIO import StringIO
import sys
import urllib2

import splunk.client as client

import utils

def request(url, message, **kwargs):
    method = message['method'].lower()
    data = message.get('body', "") if method == 'post' else None
    headers = dict(message.get('headers', []))
    context = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(context)
    except urllib2.HTTPError, response:
        pass # Propagate HTTP errors via the returned response message
    return {
        'status': response.code,
        'reason': response.msg,
        'headers': response.info().dict,
        'body': StringIO(response.read())
    }

opts = utils.parse(sys.argv[1:], {}, ".splunkrc")
service = client.connect(handler=request, **opts.kwargs)
pprint(service.apps.list())

Exemple #9
0
# 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.

"""Retrieves a list of installed apps from Splunk using the client module."""

import splunk.client as client

HOST = "localhost"
PORT = 8089
USERNAME = "******"
PASSWORD = "******"

service = client.connect(host=HOST, port=PORT, username=USERNAME, password=PASSWORD)

for app in service.apps:
    print app.name
        pass # Propagate HTTP errors via the returned response message
    return {
        'status': response.code,
        'reason': response.msg,
        'headers': response.info().dict,
        'body': StringIO(response.read())
    }

def handler(proxy):
    proxy_handler = urllib2.ProxyHandler({'http': proxy, 'https': proxy})
    opener = urllib2.build_opener(proxy_handler)
    urllib2.install_opener(opener)
    return request

opts = utils.parse(sys.argv[1:], RULES, ".splunkrc")
proxy = opts.kwargs['proxy']
try:
    service = client.connect(handler=handler(proxy), **opts.kwargs)
    pprint(service.apps.list())
except urllib2.URLError as e:
    if e.reason.errno == 1 and sys.version_info < (2, 6, 3):
        # There is a bug in Python < 2.6.3 that does not
        # allow proxies with HTTPS. As such, this test will
        # fail.
        # You can read more at the following URL:
        # http://bugs.python.org/issue1424152
        pass
    else:
        raise

    def request(url, message, **kwargs):
        scheme, host, port, path = spliturl(url)

        if scheme != "https": 
            ValueError("unsupported scheme: %s" % scheme)

        connection = HTTPSConnection(host, port, ca_file)
        try:
            body = message.get('body', "")
            headers = dict(message.get('headers', []))
            connection.request(message['method'], path, body, headers)
            response = connection.getresponse()
        finally:
            connection.close()

        return {
            'status': response.status,
            'reason': response.reason,
            'headers': response.getheaders(),
            'body': StringIO(response.read())
        }

    return request

opts = utils.parse(sys.argv[1:], RULES, ".splunkrc")
ca_file = opts.kwargs['ca_file']
service = client.connect(handler=handler(ca_file), **opts.kwargs)
pprint(service.apps.list())