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 calllogin()
. 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
) – WhenTrue
, 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")
- host (
-
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
- key_file (
-
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
andapp
and is governed by asharing
mode. The possible values forsharing
are: “user”, “app”, “global” and “system”, which map to the following combinations ofowner
andapp
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
andapp
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 usingowner={currentUser}
andapp={defaultApp}
.The
namespace
function returns a representation of the namespace from reconciling the values you provide. It ignores any keyword arguments other thanowner
,app
, andsharing
, so you can providedicts
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()
orsplunklib.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 itslogin()
method before you can issue requests to splunkd. Or, use theconnect()
function to create an already-authenticatedContext
object. You can provide a session token explicitly (the same token can be shared by multipleContext
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 calllogin()
. - cookie (
string
) – A session cookie. When provided, you don’t need to calllogin()
. 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 theautologin
field ofconnect()
is set toTrue
.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 keysbody
,headers
,reason
, andstatus
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
- AuthenticationError – Raised when the
-
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 theautologin
field ofconnect()
is set toTrue
.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 keysbody
,headers
,reason
, andstatus
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
- AuthenticationError – Raised when the
Gets the dictionary of cookies from the
HttpLib
member of this instance.Returns: Dictionary of cookies stored on the self.http
.Return type: dict
Returns true if the
HttpLib
member of this instance has auth token stored.Returns: True
if there is auth token present, elseFalse
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 differentContext
object) you must calllogin()
before you can issue requests. The authentication token obtained from the server is stored in thetoken
field of theContext
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 theautologin
field ofconnect()
is set toTrue
.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
andreceivers/stream
, require unstructured data in the POST body and all metadata passed as GET-style arguments. If you provide abody
argument topost
, 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
orstr
) – 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 keysbody
,headers
,reason
, andstatus
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')
- AuthenticationError – Raised when the
-
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 keysbody
,headers
,reason
, andstatus
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
- AuthenticationError – Raised when the
- host (
-
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 generalrequest()
method, anddelete()
,post()
, andget()
methods for the three HTTP methods that Splunk uses.By default,
HttpLib
uses Python’s built-inhttplib
library, but you can replace it by passing your own handling function to the constructor forHttpLib
.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
, orDELETE
. - 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)
andclose()
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 thehandler()
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
- url (
-
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
- url (
-
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 isbody
, the value is used as the body for the request, and the keywords and their arguments will be URL encoded. If there is nobody
keyword argument, all the keyword arguments are encoded into the body of the request in the formatx-www-form-urlencoded
.
Returns: A dictionary describing the response (see
HttpLib
for its structure).Return type: dict
- url (
-
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 inHttpLib
. - 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
- url (
- method: The method for the request, typically
-
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.
-