splunklib.binding

The splunklib.binding module provides a low-level binding interface to the Splunk REST API.

This module handles the wire details of calling the REST API, such as authentication tokens, prefix paths, URL encoding, and so on. Actual path segments, GET and POST arguments, and the parsing of responses is left to the user.

If you want a friendlier interface to the Splunk REST API, use the splunklib.client module.

splunklib.binding.connect(**kwargs)

This function returns an authenticated Context object.

This function is a shorthand for calling Context.login().

This function makes one round trip to the server.

Parameters:
  • host (string) – The host name (the default is “localhost”).
  • port (integer) – The port number (the default is 8089).
  • scheme ("https" or "http") – The scheme for accessing the service (the default is “https”).
  • owner (string) – The owner context of the namespace (the default is “None”).
  • app (string) – The app context of the namespace (the default is “None”).
  • sharing ("global", "system", "app", or "user") – The sharing mode for the namespace (the default is “user”).
  • token (string) – The current session token (optional). Session tokens can be shared across multiple service instances.
  • cookie (string) – A session cookie. When provided, you don’t need to call login(). This parameter is only supported for Splunk 6.2+.
  • username (string) – The Splunk account username, which is used to authenticate the Splunk instance.
  • password (string) – The password for the Splunk account.
  • headers (list of 2-tuples.) – List of extra HTTP headers to send (optional).
  • autologin (Boolean) – When True, automatically tries to log in again if the session terminates.
Returns:

An initialized Context instance.

Example:

import splunklib.binding as binding
c = binding.connect(...)
response = c.get("apps/local")
splunklib.binding.handler(key_file=None, cert_file=None, timeout=None, verify=False, context=None)

This class returns an instance of the default HTTP request handler using the values you provide.

Parameters:
  • key_file (string) – A path to a PEM (Privacy Enhanced Mail) formatted file containing your private key (optional).
  • cert_file (string) – A path to a PEM (Privacy Enhanced Mail) formatted file containing a certificate chain file (optional).
  • timeout (integer or “None”) – The request time-out period, in seconds (optional).
  • verify (Boolean) – Set to False to disable SSL verification on https connections.
  • context (``SSLContext`) – The SSLContext that can is used with the HTTPSConnection when verify=True is enabled and context is specified
splunklib.binding.namespace(sharing=None, owner=None, app=None, **kwargs)

This function constructs a Splunk namespace.

Every Splunk resource belongs to a namespace. The namespace is specified by the pair of values owner and app and is governed by a sharing mode. The possible values for sharing are: “user”, “app”, “global” and “system”, which map to the following combinations of owner and app values:

“user” => {owner}, {app}

“app” => nobody, {app}

“global” => nobody, {app}

“system” => nobody, system

“nobody” is a special user name that basically means no user, and “system” is the name reserved for system resources.

“-” is a wildcard that can be used for both owner and app values and refers to all users and all apps, respectively.

In general, when you specify a namespace you can specify any combination of these three values and the library will reconcile the triple, overriding the provided values as appropriate.

Finally, if no namespacing is specified the library will make use of the /services branch of the REST API, which provides a namespaced view of Splunk resources equivelent to using owner={currentUser} and app={defaultApp}.

The namespace function returns a representation of the namespace from reconciling the values you provide. It ignores any keyword arguments other than owner, app, and sharing, so you can provide dicts of configuration information without first having to extract individual keys.

Parameters:
  • sharing ("system", "global", "app", or "user") – The sharing mode (the default is “user”).
  • owner (string) – The owner context (the default is “None”).
  • app (string) – The app context (the default is “None”).
Returns:

A splunklib.data.Record containing the reconciled namespace.

Example:

import splunklib.binding as binding
n = binding.namespace(sharing="user", owner="boris", app="search")
n = binding.namespace(sharing="global", app="search")
class splunklib.binding.AuthenticationError(message, cause)

Raised when a login request to Splunk fails.

If your username was unknown or you provided an incorrect password in a call to Context.login() or splunklib.client.Service.login(), this exception is raised.

class splunklib.binding.Context(handler=None, **kwargs)

This class represents a context that encapsulates a splunkd connection.

The Context class encapsulates the details of HTTP requests, authentication, a default namespace, and URL prefixes to simplify access to the REST API.

After creating a Context object, you must call its login() method before you can issue requests to splunkd. Or, use the connect() function to create an already-authenticated Context object. You can provide a session token explicitly (the same token can be shared by multiple Context objects) to provide authentication.

Parameters:
  • host (string) – The host name (the default is “localhost”).
  • port (integer) – The port number (the default is 8089).
  • scheme ("https" or "http") – The scheme for accessing the service (the default is “https”).
  • verify (Boolean) – Enable (True) or disable (False) SSL verification for https connections.
  • self_signed_certificate (Boolean) – Specifies if self signed certificate is used
  • sharing ("global", "system", "app", or "user") – The sharing mode for the namespace (the default is “user”).
  • owner (string) – The owner context of the namespace (optional, the default is “None”).
  • app (string) – The app context of the namespace (optional, the default is “None”).
  • token (string) – A session token. When provided, you don’t need to call login().
  • cookie (string) – A session cookie. When provided, you don’t need to call login(). This parameter is only supported for Splunk 6.2+.
  • username (string) – The Splunk account username, which is used to authenticate the Splunk instance.
  • password (string) – The password for the Splunk account.
  • splunkToken (string) – Splunk authentication token
  • headers (list of 2-tuples.) – List of extra HTTP headers to send (optional).
  • retires – Number of retries for each HTTP connection (optional, the default is 0). NOTE THAT THIS MAY INCREASE THE NUMBER OF ROUND TRIP CONNECTIONS TO THE SPLUNK SERVER AND BLOCK THE CURRENT THREAD WHILE RETRYING.
  • retryDelay (int (in seconds)) – How long to wait between connection attempts if retries > 0 (optional, defaults to 10s).
  • handler – The HTTP request handler (optional).
Returns:

A Context instance.

Example:

import splunklib.binding as binding
c = binding.Context(username="boris", password="natasha", ...)
c.login()
# Or equivalently
c = binding.connect(username="boris", password="natasha")
# Or if you already have a session token
c = binding.Context(token="atg232342aa34324a")
# Or if you already have a valid cookie
c = binding.Context(cookie="splunkd_8089=...")
connect()

Returns an open connection (socket) to the Splunk instance.

This method is used for writing bulk events to an index or similar tasks where the overhead of opening a connection multiple times would be prohibitive.

Returns:A socket.

Example:

import splunklib.binding as binding
c = binding.connect(...)
socket = c.connect()
socket.write("POST %s HTTP/1.1\r\n" % "some/path/to/post/to")
socket.write("Host: %s:%s\r\n" % (c.host, c.port))
socket.write("Accept-Encoding: identity\r\n")
socket.write("Authorization: %s\r\n" % c.token)
socket.write("X-Splunk-Input-Mode: Streaming\r\n")
socket.write("\r\n")
delete(path_segment, owner=None, app=None, sharing=None, **query)

Performs a DELETE operation at the REST path segment with the given namespace and query.

This method is named to match the HTTP method. delete makes at least one round trip to the server, one additional round trip for each 303 status returned, and at most two additional round trips if the autologin field of connect() is set to True.

If owner, app, and sharing are omitted, this method uses the default Context namespace. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Context object is not logged in.
  • HTTPError – Raised when an error occurred in a GET operation from path_segment.
Parameters:
  • path_segment (string) – A REST path segment.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (string) – The sharing mode of the namespace (optional).
  • query (string) – All other keyword arguments, which are used as query parameters.
Returns:

The response from the server.

Return type:

dict with keys body, headers, reason, and status

Example:

c = binding.connect(...)
c.delete('saved/searches/boris') == \
    {'body': ...a response reader object...,
     'headers': [('content-length', '1786'),
                 ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
                 ('server', 'Splunkd'),
                 ('connection', 'close'),
                 ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
                 ('date', 'Fri, 11 May 2012 16:53:06 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'OK',
     'status': 200}
c.delete('nonexistant/path') # raises HTTPError
c.logout()
c.delete('apps/local') # raises AuthenticationError
get(path_segment, owner=None, app=None, headers=None, sharing=None, **query)

Performs a GET operation from the REST path segment with the given namespace and query.

This method is named to match the HTTP method. get makes at least one round trip to the server, one additional round trip for each 303 status returned, and at most two additional round trips if the autologin field of connect() is set to True.

If owner, app, and sharing are omitted, this method uses the default Context namespace. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Context object is not logged in.
  • HTTPError – Raised when an error occurred in a GET operation from path_segment.
Parameters:
  • path_segment (string) – A REST path segment.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • headers (list of 2-tuples.) – List of extra HTTP headers to send (optional).
  • sharing (string) – The sharing mode of the namespace (optional).
  • query (string) – All other keyword arguments, which are used as query parameters.
Returns:

The response from the server.

Return type:

dict with keys body, headers, reason, and status

Example:

c = binding.connect(...)
c.get('apps/local') == \
    {'body': ...a response reader object...,
     'headers': [('content-length', '26208'),
                 ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
                 ('server', 'Splunkd'),
                 ('connection', 'close'),
                 ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
                 ('date', 'Fri, 11 May 2012 16:30:35 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'OK',
     'status': 200}
c.get('nonexistant/path') # raises HTTPError
c.logout()
c.get('apps/local') # raises AuthenticationError
get_cookies()

Gets the dictionary of cookies from the HttpLib member of this instance.

Returns:Dictionary of cookies stored on the self.http.
Return type:dict
has_cookies()

Returns true if the HttpLib member of this instance has auth token stored.

Returns:True if there is auth token present, else False
Return type:bool
login()

Logs into the Splunk instance referred to by the Context object.

Unless a Context is created with an explicit authentication token (probably obtained by logging in from a different Context object) you must call login() before you can issue requests. The authentication token obtained from the server is stored in the token field of the Context object.

Raises:AuthenticationError – Raised when login fails.
Returns:The Context object, so you can chain calls.

Example:

import splunklib.binding as binding
c = binding.Context(...).login()
# Then issue requests...
logout()

Forgets the current session token, and cookies.

post(path_segment, owner=None, app=None, sharing=None, headers=None, **query)

Performs a POST operation from the REST path segment with the given namespace and query.

This method is named to match the HTTP method. post makes at least one round trip to the server, one additional round trip for each 303 status returned, and at most two additional round trips if the autologin field of connect() is set to True.

If owner, app, and sharing are omitted, this method uses the default Context namespace. All other keyword arguments are included in the URL as query parameters.

Some of Splunk’s endpoints, such as receivers/simple and receivers/stream, require unstructured data in the POST body and all metadata passed as GET-style arguments. If you provide a body argument to post, it will be used as the POST body, and all other keyword arguments will be passed as GET-style arguments in the URL.

Raises:
  • AuthenticationError – Raised when the Context object is not logged in.
  • HTTPError – Raised when an error occurred in a GET operation from path_segment.
Parameters:
  • path_segment (string) – A REST path segment.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (string) – The sharing mode of the namespace (optional).
  • headers (list of 2-tuples.) – List of extra HTTP headers to send (optional).
  • query – All other keyword arguments, which are used as query parameters.
  • body (dict or str) – Parameters to be used in the post body. If specified, any parameters in the query will be applied to the URL instead of the body. If a dict is supplied, the key-value pairs will be form encoded. If a string is supplied, the body will be passed through in the request unchanged.
Returns:

The response from the server.

Return type:

dict with keys body, headers, reason, and status

Example:

c = binding.connect(...)
c.post('saved/searches', name='boris',
       search='search * earliest=-1m | head 1') == \
    {'body': ...a response reader object...,
     'headers': [('content-length', '10455'),
                 ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
                 ('server', 'Splunkd'),
                 ('connection', 'close'),
                 ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
                 ('date', 'Fri, 11 May 2012 16:46:06 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
c.post('nonexistant/path') # raises HTTPError
c.logout()
# raises AuthenticationError:
c.post('saved/searches', name='boris',
       search='search * earliest=-1m | head 1')
request(path_segment, method='GET', headers=None, body={}, owner=None, app=None, sharing=None)

Issues an arbitrary HTTP request to the REST path segment.

This method is named to match httplib.request. This function makes a single round trip to the server.

If owner, app, and sharing are omitted, this method uses the default Context namespace. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Context object is not logged in.
  • HTTPError – Raised when an error occurred in a GET operation from path_segment.
Parameters:
  • path_segment (string) – A REST path segment.
  • method (string) – The HTTP method to use (optional).
  • headers (list of 2-tuples.) – List of extra HTTP headers to send (optional).
  • body (string) – Content of the HTTP request (optional).
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (string) – The sharing mode of the namespace (optional).
Returns:

The response from the server.

Return type:

dict with keys body, headers, reason, and status

Example:

c = binding.connect(...)
c.request('saved/searches', method='GET') == \
    {'body': ...a response reader object...,
     'headers': [('content-length', '46722'),
                 ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
                 ('server', 'Splunkd'),
                 ('connection', 'close'),
                 ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
                 ('date', 'Fri, 11 May 2012 17:24:19 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'OK',
     'status': 200}
c.request('nonexistant/path', method='GET') # raises HTTPError
c.logout()
c.get('apps/local') # raises AuthenticationError
class splunklib.binding.HTTPError(response, _message=None)

This exception is raised for HTTP responses that return an error.

class splunklib.binding.HttpLib(custom_handler=None, verify=False, key_file=None, cert_file=None, context=None, retries=0, retryDelay=10)

A set of convenient methods for making HTTP calls.

HttpLib provides a general request() method, and delete(), post(), and get() methods for the three HTTP methods that Splunk uses.

By default, HttpLib uses Python’s built-in httplib library, but you can replace it by passing your own handling function to the constructor for HttpLib.

The handling function should have the type:

handler(`url`, `request_dict`) -> response_dict

where url is the URL to make the request to (including any query and fragment sections) as a dictionary with the following keys:

  • method: The method for the request, typically GET, POST, or DELETE.
  • headers: A list of pairs specifying the HTTP headers (for example: [('key': value), ...]).
  • body: A string containing the body to send with the request (this string should default to ‘’).

and response_dict is a dictionary with the following keys:

  • status: An integer containing the HTTP status code (such as 200 or 404).
  • reason: The reason phrase, if any, returned by the server.
  • headers: A list of pairs containing the response headers (for example, [('key': value), ...]).
  • body: A stream-like object supporting read(size=None) and close() methods to get the body of the response.

The response dictionary is returned directly by HttpLib’s methods with no further processing. By default, HttpLib calls the handler() function to get a handler function.

If using the default handler, SSL verification can be disabled by passing verify=False.

delete(url, headers=None, **kwargs)

Sends a DELETE request to a URL.

Parameters:
  • url (string) – The URL.
  • headers (list) – A list of pairs specifying the headers for the HTTP response (for example, [('Content-Type': 'text/cthulhu'), ('Token': 'boris')]).
  • kwargs (dict) – Additional keyword arguments (optional). These arguments are interpreted as the query part of the URL. The order of keyword arguments is not preserved in the request, but the keywords and their arguments will be URL encoded.
Returns:

A dictionary describing the response (see HttpLib for its structure).

Return type:

dict

get(url, headers=None, **kwargs)

Sends a GET request to a URL.

Parameters:
  • url (string) – The URL.
  • headers (list) – A list of pairs specifying the headers for the HTTP response (for example, [('Content-Type': 'text/cthulhu'), ('Token': 'boris')]).
  • kwargs (dict) – Additional keyword arguments (optional). These arguments are interpreted as the query part of the URL. The order of keyword arguments is not preserved in the request, but the keywords and their arguments will be URL encoded.
Returns:

A dictionary describing the response (see HttpLib for its structure).

Return type:

dict

post(url, headers=None, **kwargs)

Sends a POST request to a URL.

Parameters:
  • url (string) – The URL.
  • headers (list) – A list of pairs specifying the headers for the HTTP response (for example, [('Content-Type': 'text/cthulhu'), ('Token': 'boris')]).
  • kwargs (dict) – Additional keyword arguments (optional). If the argument is body, the value is used as the body for the request, and the keywords and their arguments will be URL encoded. If there is no body keyword argument, all the keyword arguments are encoded into the body of the request in the format x-www-form-urlencoded.
Returns:

A dictionary describing the response (see HttpLib for its structure).

Return type:

dict

request(url, message, **kwargs)

Issues an HTTP request to a URL.

Parameters:
  • url (string) – The URL.
  • message (dict) – A dictionary with the format as described in HttpLib.
  • kwargs (dict) – Additional keyword arguments (optional). These arguments are passed unchanged to the handler.
Returns:

A dictionary describing the response (see HttpLib for its structure).

Return type:

dict

class splunklib.binding.ResponseReader(response, connection=None)

This class provides a file-like interface for httplib responses.

The ResponseReader class is intended to be a layer to unify the different types of HTTP libraries used with this SDK. This class also provides a preview of the stream and a few useful predicates.

close()

Closes this response.

empty

Indicates whether there is any more data in the response.

peek(size)

Nondestructively retrieves a given number of characters.

The next read() operation behaves as though this method was never called.

Parameters:size (integer) – The number of characters to retrieve.
read(size=None)

Reads a given number of characters from the response.

Parameters:size (integer or “None”) – The number of characters to read, or “None” to read the entire response.