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.
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: |
|
---|---|
Returns: | An initialized Context instance. |
Example:
import splunklib.binding as binding
c = binding.connect(...)
response = c.get("apps/local")
This class returns an instance of the default HTTP request handler using the values you provide.
Parameters: |
|
---|
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: |
|
---|---|
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")
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.
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: |
|
---|---|
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")
# Of if you already have a session token
c = binding.Context(token="atg232342aa34324a")
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")
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: |
|
---|---|
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
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: |
|
---|---|
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
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...
Forgets the current session token.
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: |
|
---|---|
Parameters: |
|
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')
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: |
|
---|---|
Parameters: |
|
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
This exception is raised for HTTP responses that return an error.
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.
Sends a DELETE request to a URL.
Parameters: |
|
---|---|
Returns: | A dictionary describing the response (see HttpLib for its structure). |
Return type: | dict |
Sends a GET request to a URL.
Parameters: |
|
---|---|
Returns: | A dictionary describing the response (see HttpLib for its structure). |
Return type: | dict |
Sends a POST request to a URL.
Parameters: |
|
---|---|
Returns: | A dictionary describing the response (see HttpLib for its structure). |
Return type: | dict |
Issues an HTTP request to a URL.
Parameters: |
|
---|---|
Returns: | A dictionary describing the response (see HttpLib for its structure). |
Return type: | dict |
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.
Closes this response.
Indicates whether there is any more data in the response.
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. |
---|
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. |
---|