def test_login_fails_without_cookie_or_token(self): opts = {"host": self.opts.kwargs["host"], "port": self.opts.kwargs["port"]} try: binding.connect(**opts) self.fail() except AuthenticationError as ae: self.assertEqual(str(ae), "Login failed.")
def test_login_fails_without_cookie_or_token(self): opts = { 'host': self.opts.kwargs['host'], 'port': self.opts.kwargs['port'] } try: binding.connect(**opts) self.fail() except AuthenticationError as ae: self.assertEqual(ae.message, "Login failed.")
def test_login_fails_without_cookie_or_token(self): opts = { 'host': self.opts.kwargs['host'], 'port': self.opts.kwargs['port'] } try: binding.connect(**opts) self.fail() except AuthenticationError as ae: self.assertEqual(str(ae), "Login failed.")
def main(): """ main entry """ options = parse(sys.argv[1:], CLIRULES, ".splunkrc") if options.kwargs['omode'] not in OUTPUT_MODES: print "output mode must be one of %s, found %s" % ( OUTPUT_MODES, options.kwargs['omode']) sys.exit(1) service = connect(**options.kwargs) if path.exists(options.kwargs['output']): if options.kwargs['recover'] == False: print "Export file %s exists, and recover option nor specified" % \ options.kwargs['output'] sys.exit(1) else: options.kwargs['end'] = recover(options) options.kwargs['fixtail'] = True openmode = "a" else: openmode = "w" options.kwargs['fixtail'] = False try: options.kwargs['fd'] = open(options.kwargs['output'], openmode) except IOError: print "Failed to open output file %s w/ mode %s" % \ (options.kwargs['output'], openmode) sys.exit(1) export(options, service)
def test_login_fails_with_bad_cookie(self): # We should get an error if using a bad cookie try: new_context = binding.connect(**{"cookie": "bad=cookie"}) self.fail() except AuthenticationError as ae: self.assertEqual(str(ae), "Login failed.")
def test_unicode_connect(self): opts = self.opts.kwargs.copy() opts['host'] = unicode(opts['host']) context = binding.connect(**opts) # Just check to make sure the service is alive response = context.get("/services") self.assertEqual(response.status, 200)
def test_unicode_connect(self): opts = self.opts.kwargs.copy() opts['host'] = six.text_type(opts['host']) context = binding.connect(**opts) # Just check to make sure the service is alive response = context.get("/services") self.assertEqual(response.status, 200)
def __init__(self, config, plugin_config): logger.info("SplunkIndexConnector:init") Connector.__init__(self, config, plugin_config) try: self.splunk_instance = config.get('splunk_login')['splunk_instance'] self.parse_url() self.splunk_username = config.get('splunk_login')['splunk_username'] self.splunk_password = config.get('splunk_login')['splunk_password'] except Exception as err: raise Exception("The Splunk instance URL or login details are not filled in. ({})".format(err)) self.splunk_app = config.get('splunk_app') self.index_name = config.get('index_name') self.search_string = config.get('search_string') self.earliest_time = config.get('earliest_time') self.latest_time = config.get('latest_time') if len(self.earliest_time) == 0: self.earliest_time = None if len(self.latest_time) == 0: self.latest_time = None logger.info('init:splunk_instance={}, index_name={}, search_string="{}", earliest_time={}, latest_time={}'.format( self.splunk_instance, self.index_name, self.search_string, self.earliest_time, self.latest_time )) args = { "host": self.splunk_host, "port": self.splunk_port, "username": self.splunk_username, "password": self.splunk_password } if not self.splunk_app == "": args["app"] = self.splunk_app self.client = connect(**args) logger.info("SplunkIndexConnector:Connected to Splunk")
def lrp_refresh(self, num_of_delays, wait_time, fargs, sargs, parallel=False): logging.debug("Starting lrp_refresh...") i = 0 if num_of_delays > 7200: num_of_delays = 7200 if wait_time > 60: wait_time = 60 #reqbody = 'cmdtype=HB&cmd=na&suser=su&spw=spw&nodelist=nl' reqbody = 'cmdtype=HB' #logging.debug ("reqbody = " + str(reqbody)) header = [('Content-Type', 'application/x-www-form-urlencoded')] service = binding.connect(token=str(sargs['authtoken'])) logging.debug("Starting lrp_refresh while loop...num_of_delays = " + str(num_of_delays) + "; wait_time = " + str(wait_time)) while i < num_of_delays: logging.debug("In lrp_refresh while loop...i = " + str(i) + "; wait_time = " + str(wait_time)) time.sleep(wait_time) logging.debug('wait delay ' + str(i) + ' complete...') response = service.request('/services/cliauto', method='POST', headers=header, body=reqbody) #response = requests.post('https://127.0.0.1/en-US/splunkd/__raw/services/cliauto', headers=self.cargs, data={'cmdtype' : 'HB'}, verify=False) response_web = requests.post('https://127.0.0.1/en-US/app/cliauto/hb', headers=self.cargs, verify=False) logging.debug('lrp_refresh call ' + str(i) + ' complete...') logging.debug('response = ' + str(response)) logging.debug('response_web = ' + str(response_web)) i += 1 logging.debug("lrp exiting...") return 0
def main(): """ main entry """ options = parse(sys.argv[1:], CLIRULES, ".splunkrc") if options.kwargs['omode'] not in OUTPUT_MODES: print "output mode must be one of %s, found %s" % (OUTPUT_MODES, options.kwargs['omode']) sys.exit(1) service = connect(**options.kwargs) if path.exists(options.kwargs['output']): if options.kwargs['recover'] == False: error("Export file exists, and recover option nor specified") else: options.kwargs['end'] = recover(options) options.kwargs['fixtail'] = True openmode = "a" else: openmode = "w" options.kwargs['fixtail'] = False try: options.kwargs['fd'] = open(options.kwargs['output'], openmode) except IOError: print "Failed to open output file %s w/ mode %s" % \ (options.kwargs['output'], openmode) sys.exit(1) export(options, service)
def test_login_fails_with_bad_cookie(self): new_context = binding.connect(**{"cookie": "bad=cookie"}) # We should get an error if using a bad cookie try: new_context.get("apps/local") self.fail() except AuthenticationError as ae: self.assertEqual(ae.message, "Request failed: Session is not logged in.")
def test_context_with_system_sharing(self): context = binding.connect(owner="me", app="MyApp", sharing="system", **self.kwargs) path = context._abspath("foo") self.assertTrue(isinstance(path, UrlEncoded)) self.assertEqual(path, "/servicesNS/nobody/system/foo")
def test_list(self): context = binding.connect(**self.opts.kwargs) response = context.get(PATH_USERS) self.assertEqual(response.status, 200) response = context.get(PATH_USERS + "/_new") self.assertEqual(response.status, 200)
def main(argv): opts = parse(argv, {}, ".splunkrc") context = connect(**opts.kwargs) service = Service(context) assert service.apps().status == 200 assert service.indexes().status == 200 assert service.info().status == 200 assert service.settings().status == 200 assert service.search("search 404").status == 200
def test_post_with_body_urlencoded(self): def check_response(handler): length = int(handler.headers.get('content-length', 0)) body = handler.rfile.read(length) assert six.ensure_str(body) == "foo=bar" with MockServer(POST=check_response): ctx = binding.connect(port=9093, scheme='http', token="waffle") ctx.post("/", foo="bar")
def test_login_fails_with_bad_cookie(self): new_context = binding.connect(**{"cookie": "bad=cookie"}) # We should get an error if using a bad cookie try: new_context.get("apps/local") self.fail() except AuthenticationError as ae: self.assertEqual(str(ae), "Request failed: Session is not logged in.")
def test_connect(self): context = binding.connect(**self.opts.kwargs) # Just check to make sure the service is alive response = context.get("/services") self.assertEqual(response.status, 200) # Make sure we can open a socket to the service context.connect().close()
def test_handlers(self): paths = ["/services", "authentication/users", "search/jobs"] handlers = [binding.handler(), urllib2_handler] # default handler for handler in handlers: logging.debug("Connecting with handler %s", handler) context = binding.connect(handler=handler, **self.opts.kwargs) for path in paths: body = context.get(path).body.read() self.assertTrue(isatom(body))
def setUp(self): self.opts = testlib.parse([], {}, ".splunkrc") opts = self.opts.kwargs.copy() opts["basic"] = True opts["username"] = self.opts.kwargs["username"] opts["password"] = self.opts.kwargs["password"] self.context = binding.connect(**opts) import splunklib.client as client service = client.Service(**opts)
def setUp(self): self.opts = testlib.parse([], {}, ".splunkrc") self.context = binding.connect(**self.opts.kwargs) # Skip these tests if running below Splunk 6.2, cookie-auth didn't exist before import splunklib.client as client service = client.Service(**self.opts.kwargs) splver = service.splunk_version if splver[:2] < (6, 2): self.skipTest("Skipping cookie-auth tests, running in %d.%d.%d, this feature was added in 6.2+" % splver)
def main(argv): """ main entry """ usage = 'usage: %prog --help for options' opts = utils.parse(argv, RULES, ".splunkrc", usage=usage) context = binding.connect(**opts.kwargs) operation = None # splunk.binding.debug = True # for verbose information (helpful for debugging) # Extract from command line and build into variable args kwargs = {} for key in RULES.keys(): if key in opts.kwargs: if key == "operation": operation = opts.kwargs[key] else: kwargs[key] = opts.kwargs[key] # no operation? if name present, default to list, otherwise list-all if not operation: if 'name' in kwargs: operation = 'list' else: operation = 'list-all' # pre-sanitize if (operation != "list" and operation != "create" and operation != "delete" and operation != "list-all"): print("operation %s not one of list-all, list, create, delete" % operation) sys.exit(0) if 'name' not in kwargs and operation != "list-all": print("operation requires a name") sys.exit(0) # remove arg 'name' from passing through to operation builder, except on create if operation != "create" and operation != "list-all": name = kwargs['name'] kwargs.pop('name') # perform operation on saved search created with args from cli if operation == "list-all": result = context.get("saved/searches", **kwargs) elif operation == "list": result = context.get("saved/searches/%s" % name, **kwargs) elif operation == "create": result = context.post("saved/searches", **kwargs) else: result = context.delete("saved/searches/%s" % name, **kwargs) print("HTTP STATUS: %d" % result.status) xml_data = result.body.read().decode('utf-8') sys.stdout.write(xml_data)
def main(argv): """ main entry """ usage = 'usage: %prog --help for options' opts = utils.parse(argv, RULES, ".splunkrc", usage=usage) context = binding.connect(**opts.kwargs) operation = None # splunk.binding.debug = True # for verbose information (helpful for debugging) # Extract from command line and build into variable args kwargs = {} for key in RULES.keys(): if opts.kwargs.has_key(key): if key == "operation": operation = opts.kwargs[key] else: kwargs[key] = urllib.quote(opts.kwargs[key]) # no operation? if name present, default to list, otherwise list-all if not operation: if kwargs.has_key('name'): operation = 'list' else: operation = 'list-all' # pre-sanitize if (operation != "list" and operation != "create" and operation != "delete" and operation != "list-all"): print "operation %s not one of list-all, list, create, delete" % operation sys.exit(0) if not kwargs.has_key('name') and operation != "list-all": print "operation requires a name" sys.exit(0) # remove arg 'name' from passing through to operation builder, except on create if operation != "create" and operation != "list-all": name = kwargs['name'] kwargs.pop('name') # perform operation on saved search created with args from cli if operation == "list-all": result = context.get("saved/searches", **kwargs) elif operation == "list": result = context.get("saved/searches/%s" % name, **kwargs) elif operation == "create": result = context.post("saved/searches", **kwargs) else: result = context.delete("saved/searches/%s" % name, **kwargs) print "HTTP STATUS: %d" % result.status xml_data = result.body.read() sys.stdout.write(xml_data)
def test_create(self): context = binding.connect(**self.opts.kwargs) username = "******" password = "******" roles = "power" try: response = context.delete(PATH_USERS + username) self.assertEqual(response.status, 200) except HTTPError, e: self.assertEqual(e.status, 400) # User doesnt exist
def test_logout(self): context = binding.connect(**self.opts.kwargs) response = context.get("/services") self.assertEqual(response.status, 200) context.logout() try: context.get("/services") self.fail() except HTTPError, e: self.assertEqual(e.status, 401)
def setUp(self): self.opts = testlib.parse([], {}, ".splunkrc") self.context = binding.connect(**self.opts.kwargs) # Skip these tests if running below Splunk 6.2, cookie-auth didn't exist before import splunklib.client as client service = client.Service(**self.opts.kwargs) splver = service.splunk_version if splver[:2] < (6, 2): self.skipTest( "Skipping cookie-auth tests, running in %d.%d.%d, this feature was added in 6.2+" % splver)
def test_post_with_body_dict(self): def check_response(handler): length = int(handler.headers.get('content-length', 0)) body = handler.rfile.read(length) assert six.ensure_str(handler.headers['content-type'] ) == 'application/x-www-form-urlencoded' assert six.ensure_str(body) == 'baz=baf&hep=cat' or six.ensure_str( body) == 'hep=cat&baz=baf' with MockServer(POST=check_response): ctx = binding.connect(port=9093, scheme='http', token="waffle") ctx.post("/", foo="bar", body={"baz": "baf", "hep": "cat"})
def test_handlers(self): paths = ["/services", "authentication/users", "search/jobs"] handlers = [ binding.handler(), # default handler urllib2_handler ] for handler in handlers: logging.debug("Connecting with handler %s", handler) context = binding.connect(handler=handler, **self.opts.kwargs) for path in paths: body = context.get(path).body.read() self.assertTrue(isatom(body))
def setUp(self): self.opts = testlib.parse([], {}, ".env") self.context = binding.connect(**self.opts.kwargs) # Skip these tests if running below Splunk 6.2, cookie-auth didn't exist before import splunklib.client as client service = client.Service(**self.opts.kwargs) # TODO: Workaround the fact that skipTest is not defined by unittest2.TestCase service.login() splver = service.splunk_version if splver[:2] < (6, 2): self.skipTest( "Skipping cookie-auth tests, running in %d.%d.%d, this feature was added in 6.2+" % splver)
def __init__(self, sargs): # Processing the request try: self.status = "Failure" logging.info('Creating cliauto_access...') self.sargs = sargs self.service = binding.connect(token=self.sargs['authtoken']) logging.debug('self.service = ' + str(self.service)) self.status = "Success" except Exception as err: logging.error('Error, Creating cliauto_access, err = ' + str(err)) self.status = 'Error, Creating cliauto_access, err = ' + str(err)
def test_post_with_body_string(self): def check_response(handler): length = int(handler.headers.get('content-length', 0)) body = handler.rfile.read(length) assert six.ensure_str( handler.headers['content-type']) == 'application/json' assert json.loads(body)["baz"] == "baf" with MockServer(POST=check_response): ctx = binding.connect(port=9093, scheme='http', token="waffle", headers=[("Content-Type", "application/json") ]) ctx.post("/", foo="bar", body='{"baz": "baf"}')
def test_connect_with_preexisting_token_sans_user_and_pass(self): token = self.context.token opts = self.opts.kwargs.copy() del opts["username"] del opts["password"] opts["token"] = token newContext = binding.connect(**opts) response = newContext.get("/services") self.assertEqual(response.status, 200) socket = newContext.connect() socket.write("POST %s HTTP/1.1\r\n" % self.context._abspath("some/path/to/post/to")) socket.write("Host: %s:%s\r\n" % (self.context.host, self.context.port)) socket.write("Accept-Encoding: identity\r\n") socket.write("Authorization: %s\r\n" % self.context.token) socket.write("X-Splunk-Input-Mode: Streaming\r\n") socket.write("\r\n") socket.close()
def __init__(self, config, plugin_config): logger.info("SplunkIndexExporterConnector:init") Connector.__init__(self, config, plugin_config) try: self.splunk_instance = config.get( 'splunk_login')['splunk_instance'] self.parse_url() self.splunk_username = config.get( 'splunk_login')['splunk_username'] self.splunk_password = config.get( 'splunk_login')['splunk_password'] except Exception as err: raise Exception( "The Splunk instance URL or login details are not filled in. ({})" .format(err)) self.splunk_app = config.get('splunk_app') self.index_name = config.get('index_name').lower() self.search_string = "" self.splunk_sourcetype = config.get('splunk_sourcetype') self.source_host = config.get("source_host", "dss") self.overwrite_existing_index = config.get('overwrite_existing_index', False) self.earliest_time = None self.latest_time = None logger.info( 'init:splunk_instance={}, index_name={}, search_string="{}", earliest_time={}, latest_time={}' .format(self.splunk_instance, self.index_name, self.search_string, self.earliest_time, self.latest_time)) args = { "host": self.splunk_host, "port": self.splunk_port, "username": self.splunk_username, "password": self.splunk_password } if not self.splunk_app == "": args["app"] = self.splunk_app self.client = connect(**args) logger.info("SplunkIndexExporterConnector:Connected to Splunk") self.authorization_token = self.client.token
def test_login_with_multiple_cookies(self): bad_cookie = 'bad=cookie' new_context = binding.connect(**{"cookie": bad_cookie}) # We should get an error if using a bad cookie try: new_context.get("apps/local") self.fail() except AuthenticationError as ae: self.assertEqual(ae.message, "Request failed: Session is not logged in.") # Bring in a valid cookie now for key, value in self.context.get_cookies().items(): new_context.get_cookies()[key] = value self.assertEqual(len(new_context.get_cookies()), 2) self.assertTrue('bad' in new_context.get_cookies().keys()) self.assertTrue('cookie' in new_context.get_cookies().values()) for k, v in self.context.get_cookies().items(): self.assertEqual(new_context.get_cookies()[k], v) self.assertEqual(new_context.get("apps/local").status, 200)
def test_connect_with_preexisting_token_sans_user_and_pass(self): token = self.context.token opts = self.opts.kwargs.copy() del opts['username'] del opts['password'] opts["token"] = token newContext = binding.connect(**opts) response = newContext.get('/services') self.assertEqual(response.status, 200) socket = newContext.connect() socket.write(("POST %s HTTP/1.1\r\n" % \ self.context._abspath("some/path/to/post/to")).encode('utf-8')) socket.write(("Host: %s:%s\r\n" % \ (self.context.host, self.context.port)).encode('utf-8')) socket.write("Accept-Encoding: identity\r\n".encode('utf-8')) socket.write(("Authorization: %s\r\n" % \ self.context.token).encode('utf-8')) socket.write("X-Splunk-Input-Mode: Streaming\r\n".encode('utf-8')) socket.write("\r\n".encode('utf-8')) socket.close()
def test_login_with_multiple_cookies(self): bad_cookie = 'bad=cookie' new_context = binding.connect(**{"cookie": bad_cookie}) # We should get an error if using a bad cookie try: new_context.get("apps/local") self.fail() except AuthenticationError as ae: self.assertEqual(str(ae), "Request failed: Session is not logged in.") # Bring in a valid cookie now for key, value in self.context.get_cookies().items(): new_context.get_cookies()[key] = value self.assertEqual(len(new_context.get_cookies()), 2) self.assertTrue('bad' in new_context.get_cookies().keys()) self.assertTrue('cookie' in new_context.get_cookies().values()) for k, v in self.context.get_cookies().items(): self.assertEqual(new_context.get_cookies()[k], v) self.assertEqual(new_context.get("apps/local").status, 200)
def __init__(self, config, plugin_config): """ :param config: the dict of the configuration of the object :param plugin_config: contains the plugin settings """ logger.info("SplunkIndexExporter:Init") self.config = config self.plugin_config = plugin_config self.splunk_socket = None self.dataset_schema = None self.row_index = 0 try: self.splunk_instance = config.get('splunk_login')['splunk_instance'] self.parse_url() self.splunk_username = config.get('splunk_login')['splunk_username'] self.splunk_password = config.get('splunk_login')['splunk_password'] except Exception as err: raise Exception("The Splunk instance URL or login details are not filled in. ({})".format(err)) self.splunk_app = config.get('splunk_app') self.index_name = config.get('index_name').lower() self.search_string = "" self.splunk_sourcetype = config.get('splunk_sourcetype') self.source_host = config.get("source_host", "dss") self.overwrite_existing_index = config.get('overwrite_existing_index', False) args = { "host": self.splunk_host, "port": self.splunk_port, "username": self.splunk_username, "password": self.splunk_password } if not self.splunk_app == "": args["app"] = self.splunk_app self.client = connect(**args) logger.info("SplunkIndexExporter:Connected to Splunk") self.authorization_token = self.client.token
def test_context_with_both(self): context = binding.connect(owner="me", app="MyApp", **self.kwargs) path = context._abspath("foo") self.assertTrue(isinstance(path, UrlEncoded)) self.assertEqual(path, "/servicesNS/me/MyApp/foo")
def get_any_item(items): for item in items: return item fargs = {'tpw': '', u'spw': u'spw2', u'cmdtype': u'CLI', u'cmd': u'uptime', 'tuser': '', u'suser': u'su2', u'nodelist': u'nl2'} sargs = {u'user': u'admin', u'authtoken': u'S6A1zabz^k4vP1jZB9RaVvDQXITZmjMos4b7YMPME3JDc7lwr9prD9qvqfhhZM6WW2AQaJgA356o_PFfmhfKIsLd0BeOnaXSbl9SCk30NysExL1ZgRIRZorHPNfX'} cur_parallel_ssh_results = {} cur_parallel_ssh_results['127.0.0.1'] = {'resultstatus': 'Test', 'iteration': 1, 'host': 'Splunk_Training', 'ip_address': '127.0.0.1', 'result': 'test', 'resultraw': 'total 8\r\n-rw-------. 1 root root 1575 Sep 19 09:24 anaconda-ks.cfg\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Desktop\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Documents\r\ndrwxr-xr-x. 4 root root 199 Sep 19 12:02 Downloads\r\n-rw-r--r--. 1 root root 1623 Sep 19 09:27 initial-setup-ks.cfg\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Music\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Pictures\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Public\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Templates\r\ndrwxr-xr-x. 2 root root 6 Sep 19 09:28 Videos\r\n'} print str(type(cur_parallel_ssh_results)) print (str(type(cur_parallel_ssh_results['127.0.0.1']))) print("cur_parallel_ssh_results[host] = " + str(cur_parallel_ssh_results['127.0.0.1'])) pdb.set_trace() serviceb = binding.connect(token=sargs['authtoken']) sk = cliauto_kvstore(serviceb) gk = sk.get_items("/servicesNS/nobody/cliauto/storage/collections/data/cliauto_pid_collection") print ("gk[0] = " + str(gk[0])) #print ("gk[1] = " + str(gk[1])) item = get_any_item(gk[1]) data = str(cur_parallel_ssh_results['127.0.0.1']['result']) #data = "test1" print("data = " + str(data)) service = client.connect(token=sargs['authtoken']) pdb.set_trace() #ci = cliauto_index(service, "main", sargs) ci = cliauto_index(service, "main") if ci.status != "Success": print("Unable to create cliauto_index to write results to index")
# under the License. """Retrieves a list of installed apps from Splunk using the binding module.""" import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) from xml.etree import ElementTree import splunklib.binding as binding HOST = "localhost" PORT = 8089 USERNAME = "******" PASSWORD = "******" context = binding.connect(host=HOST, port=PORT, username=USERNAME, password=PASSWORD) response = context.get('apps/local') if response.status != 200: raise Exception, "%d (%s)" % (response.status, response.reason) body = response.body.read() data = ElementTree.XML(body) apps = data.findall( "{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title") for app in apps: print app.text
def setUp(self): logging.info("%s", self.__class__.__name__) self.opts = testlib.parse([], {}, ".splunkrc") self.context = binding.connect(**self.opts.kwargs) logging.debug("Connected to splunkd.")
def test_context_with_system_sharing(self): context = binding.connect( owner="me", app="MyApp", sharing="system", **self.kwargs) path = context._abspath("foo") self.assertTrue(isinstance(path, UrlEncoded)) self.assertEqual(path, "/servicesNS/nobody/system/foo")
def test_context_with_owner_as_email(self): context = binding.connect(owner="*****@*****.**", **self.kwargs) path = context._abspath("foo") self.assertTrue(isinstance(path, UrlEncoded)) self.assertEqual(path, "/servicesNS/me%40me.com/system/foo") self.assertEqual(path, UrlEncoded("/servicesNS/[email protected]/system/foo"))
def test_fullpath(self): context = binding.connect(**self.opts.kwargs) # Verify that Context.fullpath works as expected. path = context.fullpath("foo", owner=None, app=None) self.assertEqual(path, "/services/foo") path = context.fullpath("foo", owner="me", app=None) self.assertEqual(path, "/servicesNS/me/-/foo") path = context.fullpath("foo", owner=None, app="MyApp") self.assertEqual(path, "/servicesNS/-/MyApp/foo") path = context.fullpath("foo", owner="me", app="MyApp") self.assertEqual(path, "/servicesNS/me/MyApp/foo") path = context.fullpath("foo", owner="me", app="MyApp", sharing=None) self.assertEqual(path, "/servicesNS/me/MyApp/foo") path = context.fullpath("foo", owner="me", app="MyApp", sharing="user") self.assertEqual(path, "/servicesNS/me/MyApp/foo") path = context.fullpath("foo", owner="me", app="MyApp", sharing="app") self.assertEqual(path, "/servicesNS/nobody/MyApp/foo") path = context.fullpath("foo", owner="me", app="MyApp",sharing="global") self.assertEqual(path, "/servicesNS/nobody/MyApp/foo") path = context.fullpath("foo", owner="me", app="MyApp",sharing="system") self.assertEqual(path, "/servicesNS/nobody/system/foo") # Verify constructing resource paths using context defaults kwargs = self.opts.kwargs.copy() if 'app' in kwargs: del kwargs['app'] if 'owner' in kwargs: del kwargs['owner'] context = binding.connect(**kwargs) path = context.fullpath("foo") self.assertEqual(path, "/services/foo") context = binding.connect(owner="me", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/me/-/foo") context = binding.connect(app="MyApp", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/-/MyApp/foo") context = binding.connect(owner="me", app="MyApp", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/me/MyApp/foo") context = binding.connect( owner="me", app="MyApp", sharing=None, **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/me/MyApp/foo") context = binding.connect( owner="me", app="MyApp", sharing="user", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/me/MyApp/foo") context = binding.connect( owner="me", app="MyApp", sharing="app", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/nobody/MyApp/foo") context = binding.connect( owner="me", app="MyApp", sharing="global", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/nobody/MyApp/foo") context = binding.connect( owner="me", app="MyApp", sharing="system", **kwargs) path = context.fullpath("foo") self.assertEqual(path, "/servicesNS/nobody/system/foo")
def test_context_defaults(self): context = binding.connect(**self.kwargs) path = context._abspath("foo") self.assertTrue(isinstance(path, UrlEncoded)) self.assertEqual(path, "/services/foo")
def enable_savedsearch(self, addon_name, savedsearch): splunk_binding = binding.connect(**self.splunk) splunk_binding.post( f"/servicesNS/nobody/{addon_name}/saved/searches/{savedsearch}/enable", data='')
"""Retrieves a list of installed apps from Splunk using the binding module.""" import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) from xml.etree import ElementTree import splunklib.binding as binding HOST = "localhost" PORT = 8089 USERNAME = "******" PASSWORD = "******" context = binding.connect( host=HOST, port=PORT, username=USERNAME, password=PASSWORD) response = context.get('apps/local') if response.status != 200: raise Exception, "%d (%s)" % (response.status, response.reason) body = response.body.read() data = ElementTree.XML(body) apps = data.findall("{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title") for app in apps: print app.text
def main(): """ main entry """ # perform idmpotent login/connect -- get login creds from ~/.splunkrc # if not specified in the command line arguments. options = parse(sys.argv[1:], CLIRULES, ".splunkrc") if options.kwargs['omode'] not in OUTPUT_MODES: print "output mode must be one of %s, found %s" % (OUTPUT_MODES, options.kwargs['omode']) sys.exit(1) # minor sanity check on start/end time try: int(options.kwargs['start']) int(options.kwargs['end']) except ValueError: print "ERROR: start and end times most be expressed as an integer." print " An integer that represents seconds from 1970." sys.exit(1) connection = connect(**options.kwargs) # get lower level context. context = binding.connect( host=connection.host, username=connection.username, password=connection.password) # open restart file. rfd = None try: rfd = open(RESTART_FILE, "r") except IOError: pass # check request and environment for sanity. if options.kwargs['restart'] is not False and rfd is None: print "Failed to open restart file %s for reading" % RESTART_FILE sys.exit(1) elif options.kwargs['restart'] is False and rfd is not None: print "Warning: restart file %s exists." % RESTART_FILE print " manually remove this file to continue complete export" print " or use --restart=1 to continue export" sys.exit(1) else: pass # close restart file. if rfd is not None: rfd.close() # normalize buckets to contain no more than "limit" events per bucket # however, there may be a situation where there will be more events in # our smallest bucket (one second) -- but there is not much we are going # to do about it. bucket_list = normalize_export_buckets(options, context) # # if we have a restart in progress, we should spend some time to validate # the export by examining the last bit of the exported file versus the # restart log we have so far. # if options.kwargs['restart'] is not False: (bucket_list, sane) = validate_export(options, bucket_list) if sane is False: print "Failed to validate export, consistency check failed" sys.exit(1) # open export for writing, unless we are restarting the export, # In which case we append to the export. mode = "w" if options.kwargs['restart'] is not False: mode = "a" try: options.kwargs['fd'] = open(options.kwargs['output'], mode) except IOError: print "Failed to open output file %s w/ mode %s" % \ (options.kwargs['output'], mode) sys.exit(1) # chunk through each bucket, and on success, remove the restart file. if export(options, context, bucket_list) is True: os.remove(RESTART_FILE)
def invoke(path, **kwargs): method = kwargs.get("method", "GET") return binding.connect(**kwargs).request(path, method=method)
def invoke(path, **kwargs): message = { "method": kwargs.get("method", "GET"), } return binding.connect(**kwargs).request(path, message)