splunklib.client

The splunklib.client module provides a Pythonic interface to the Splunk REST API, allowing you programmatically access Splunk’s resources.

splunklib.client wraps a Pythonic layer around the wire-level binding of the splunklib.binding module. The core of the library is the Service class, which encapsulates a connection to the server, and provides access to the various aspects of Splunk’s functionality, which are exposed via the REST API. Typically you connect to a running Splunk instance with the connect() function:

import splunklib.client as client
service = client.connect(host='localhost', port=8089,
                   username='admin', password='...')
assert isinstance(service, client.Service)

Service objects have fields for the various Splunk resources (such as apps, jobs, saved searches, inputs, and indexes). All of these fields are Collection objects:

appcollection = service.apps
my_app = appcollection.create('my_app')
my_app = appcollection['my_app']
appcollection.delete('my_app')

The individual elements of the collection, in this case applications, are subclasses of Entity. An Entity object has fields for its attributes, and methods that are specific to each kind of entity. For example:

print my_app['author']  # Or: print my_app.author
my_app.package()  # Creates a compressed package of this application
splunklib.client.connect(**kwargs)

This function connects and logs in to a Splunk instance.

This function is a shorthand for Service.login(). The connect function makes one round trip to the server (for logging in).

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 (optional).
  • app (string) – The app context of the namespace (optional).
  • 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.
  • autologin (boolean) – When True, automatically tries to log in again if the session terminates.
  • username (string) – The Splunk account username, which is used to authenticate the Splunk instance.
  • password (string) – The password for the Splunk account.
Returns:

An initialized Service connection.

Example:

import splunklib.client as client
s = client.connect(...)
a = s.apps["my_app"]
...
class splunklib.client.AmbiguousReferenceException

Thrown when the name used to fetch an entity matches more than one entity.

class splunklib.client.Application(service, path, **kwargs)

Represents a locally-installed Splunk app.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
package()

Creates a compressed package of the app for archiving.

read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

setupInfo

Returns the setup information for the app.

Returns:The setup information.
state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
updateInfo()

Returns any update information that is available for the app.

class splunklib.client.AlertGroup(service, path, **kwargs)

This class represents a group of fired alerts for a saved search. Access it using the alerts() property.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
alerts

Returns a collection of triggered alerts.

Returns:A Collection of triggered alerts.
content

Returns the contents of the entity.

Returns:A dict containing values.
count

Returns the count of triggered alerts.

Returns:The triggered alert count.
Return type:integer
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
class splunklib.client.Collection(service, path, item=<class 'splunklib.client.Entity'>)

A collection of entities.

Splunk provides a number of different collections of distinct entity types: applications, saved searches, fired alerts, and a number of others. Each particular type is available separately from the Splunk instance, and the entities of that type are returned in a Collection.

The interface for Collection does not quite match either list or dict in Python, because there are enough semantic mismatches with either to make its behavior surprising. A unique element in a Collection is defined by a string giving its name plus namespace (although the namespace is optional if the name is unique).

Example:

import splunklib.client as client
service = client.connect(...)
mycollection = service.saved_searches
mysearch = mycollection['my_search', client.namespace(owner='boris', app='natasha', sharing='user')]
# Or if there is only one search visible named 'my_search'
mysearch = mycollection['my_search']

Similarly, name in mycollection works as you might expect (though you cannot currently pass a namespace to the in operator), as does len(mycollection).

However, as an aggregate, Collection behaves more like a list. If you iterate over a Collection, you get an iterator over the entities, not the names and namespaces.

Example:

for entity in mycollection:
    assert isinstance(entity, client.Entity)

Use the create() and delete() methods to create and delete entities in this collection. To view the access control list and other metadata of the collection, use the ReadOnlyCollection.itemmeta() method.

Collection does no caching. Each call makes at least one round trip to the server to fetch data.

create(name, **params)

Creates a new entity in this collection.

This function makes either one or two roundtrips to the server, depending on the type of entities in this collection, plus at most two more if the autologin field of connect() is set to True.

Parameters:
  • name (string) – The name of the entity to create.
  • namespace (A splunklib.data.Record object with keys owner, app, and sharing.) – A namespace, as created by the splunklib.binding.namespace() function (optional). You can also set owner, app, and sharing in params.
  • params (dict) – Additional entity-specific arguments (optional).
Returns:

The new entity.

Return type:

A subclass of Entity, chosen by Collection.self.item().

Example:

import splunklib.client as client
s = client.connect(...)
applications = s.apps
new_app = applications.create("my_fake_app")
delete(name, **params)

Deletes a specified entity from the collection.

Parameters:name (string) – The name of the entity to delete.
Returns:The collection.
Return type:self

This method is implemented for consistency with the REST API’s DELETE method.

If there is no name entity on the server, a KeyError is thrown. This function always makes a roundtrip to the server.

Example:

import splunklib.client as client
c = client.connect(...)
saved_searches = c.saved_searches
saved_searches.create('my_saved_search',
                      'search * | head 1')
assert 'my_saved_search' in saved_searches
saved_searches.delete('my_saved_search')
assert 'my_saved_search' not in saved_searches
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.ConfigurationFile(service, path, **kwargs)

This class contains all of the stanzas from one configuration file.

create(name, **params)

Creates a new entity in this collection.

This function makes either one or two roundtrips to the server, depending on the type of entities in this collection, plus at most two more if the autologin field of connect() is set to True.

Parameters:
  • name (string) – The name of the entity to create.
  • namespace (A splunklib.data.Record object with keys owner, app, and sharing.) – A namespace, as created by the splunklib.binding.namespace() function (optional). You can also set owner, app, and sharing in params.
  • params (dict) – Additional entity-specific arguments (optional).
Returns:

The new entity.

Return type:

A subclass of Entity, chosen by Collection.self.item().

Example:

import splunklib.client as client
s = client.connect(...)
applications = s.apps
new_app = applications.create("my_fake_app")
delete(name, **params)

Deletes a specified entity from the collection.

Parameters:name (string) – The name of the entity to delete.
Returns:The collection.
Return type:self

This method is implemented for consistency with the REST API’s DELETE method.

If there is no name entity on the server, a KeyError is thrown. This function always makes a roundtrip to the server.

Example:

import splunklib.client as client
c = client.connect(...)
saved_searches = c.saved_searches
saved_searches.create('my_saved_search',
                      'search * | head 1')
assert 'my_saved_search' in saved_searches
saved_searches.delete('my_saved_search')
assert 'my_saved_search' not in saved_searches
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Configurations(service)

This class provides access to the configuration files from this Splunk instance. Retrieve this collection using Service.confs().

Splunk’s configuration is divided into files, and each file into stanzas. This collection is unusual in that the values in it are themselves collections of ConfigurationFile objects.

create(name)

Creates a configuration file named name.

If there is already a configuration file with that name, the existing file is returned.

Parameters:name (string) – The name of the configuration file.
Returns:The ConfigurationFile object.
delete(key)

Raises IllegalOperationException.

get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Endpoint(service, path)

This class represents individual Splunk resources in the Splunk REST API.

An Endpoint object represents a URI, such as /services/saved/searches. This class provides the common functionality of Collection and Entity (essentially HTTP GET and POST methods).

get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
post(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Entity(service, path, **kwargs)

This class is a base class for Splunk entities in the REST API, such as saved searches, jobs, indexes, and inputs.

Entity provides the majority of functionality required by entities. Subclasses only implement the special cases for individual entities. For example for deployment serverclasses, the subclass makes whitelists and blacklists into Python lists.

An Entity is addressed like a dictionary, with a few extensions, so the following all work:

ent['email.action']
ent['disabled']
ent['whitelist']

Many endpoints have values that share a prefix, such as email.to, email.action, and email.subject. You can extract the whole fields, or use the key email to get a dictionary of all the subelements. That is, ent['email'] returns a dictionary with the keys to, action, subject, and so on. If there are multiple levels of dots, each level is made into a subdictionary, so email.body.salutation can be accessed at ent['email']['body']['salutation'] or ent['email.body.salutation'].

You can also access the fields as though they were the fields of a Python object, as in:

ent.email.action
ent.disabled
ent.whitelist

However, because some of the field names are not valid Python identifiers, the dictionary-like syntax is preferrable.

The state of an Entity object is cached, so accessing a field does not contact the server. If you think the values on the server have changed, call the Entity.refresh() method.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
class splunklib.client.IllegalOperationException

Thrown when an operation is not possible on the Splunk instance that a Service object is connected to.

class splunklib.client.IncomparableException

Thrown when trying to compare objects (using ==, <, >, and so on) of a type that doesn’t support it.

class splunklib.client.Index(service, path, **kwargs)

This class represents an index and provides different operations, such as cleaning the index, writing to the index, and so forth.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
attach(host=None, source=None, sourcetype=None)

Opens a stream (a writable socket) for writing events to the index.

Parameters:
  • host (string) – The host value for events written to the stream.
  • source (string) – The source value for events written to the stream.
  • sourcetype (string) – The sourcetype value for events written to the stream.
Returns:

A writable socket.

attached_socket(*args, **kwds)

Opens a raw socket in a with block to write data to Splunk.

The arguments are identical to those for attach(). The socket is automatically closed at the end of the with block, even if an exception is raised in the block.

Parameters:
  • host (string) – The host value for events written to the stream.
  • source (string) – The source value for events written to the stream.
  • sourcetype (string) – The sourcetype value for events written to the stream.
Returns:

Nothing.

Example:

import splunklib.client as client
s = client.connect(...)
index = s.indexes['some_index']
with index.attached_socket(sourcetype='test') as sock:
    sock.send('Test event\r\n')
clean(timeout=60)

Deletes the contents of the index.

This method blocks until the index is empty, because it needs to restore values at the end of the operation.

Parameters:timeout (integer) – The time-out period for the operation, in seconds (the default is 60).
Returns:The Index.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

roll_hot_buckets()

Performs rolling hot buckets for this index.

Returns:The Index.
state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
submit(event, host=None, source=None, sourcetype=None)

Submits a single event to the index using HTTP POST.

Parameters:
  • event (string) – The event to submit.
  • host (string) – The host value of the event.
  • source (string) – The source value of the event.
  • sourcetype (string) – The sourcetype value of the event.
Returns:

The Index.

update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
upload(filename, **kwargs)

Uploads a file for immediate indexing.

Note: The file must be locally accessible from the server.

Parameters:
  • filename (string) – The name of the file to upload. The file can be a plain, compressed, or archived file.
  • kwargs (dict) – Additional arguments (optional). For more about the available parameters, see Index parameters on Splunk Developer Portal.
Returns:

The Index.

class splunklib.client.Indexes(service, path, item=<class 'splunklib.client.Entity'>)

This class contains the collection of indexes in this Splunk instance. Retrieve this collection using Service.indexes().

create(name, **params)

Creates a new entity in this collection.

This function makes either one or two roundtrips to the server, depending on the type of entities in this collection, plus at most two more if the autologin field of connect() is set to True.

Parameters:
  • name (string) – The name of the entity to create.
  • namespace (A splunklib.data.Record object with keys owner, app, and sharing.) – A namespace, as created by the splunklib.binding.namespace() function (optional). You can also set owner, app, and sharing in params.
  • params (dict) – Additional entity-specific arguments (optional).
Returns:

The new entity.

Return type:

A subclass of Entity, chosen by Collection.self.item().

Example:

import splunklib.client as client
s = client.connect(...)
applications = s.apps
new_app = applications.create("my_fake_app")
delete(name)

Deletes a given index.

Note: This method is only supported in Splunk 5.0 and later.

Parameters:name (string) – The name of the index to delete.
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
get_default()

Returns the name of the default index.

Returns:The name of the default index.
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Input(service, path, kind=None, **kwargs)

This class represents a Splunk input. This class is the base for all typed input classes and is also used when the client does not recognize an input kind.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current input along with any additional arguments you specify.

Parameters:kwargs (dict) – Additional arguments (optional). For more about the available parameters, see Input parameters on Splunk Developer Portal.
Returns:The input this method was called on.
Return type:class:Input
class splunklib.client.Inputs(service, kindmap=None)

This class represents a collection of inputs. The collection is heterogeneous and each member of the collection contains a kind property that indicates the specific type of input. Retrieve this collection using Service.inputs().

create(name, kind, **kwargs)

Creates an input of a specific kind in this collection, with any arguments you specify.

Parameters:
  • name (string) – The input name.
  • kind (string) –

    The kind of input:

    • “ad”: Active Directory
    • “monitor”: Files and directories
    • “registry”: Windows Registry
    • “script”: Scripts
    • “splunktcp”: TCP, processed
    • “tcp”: TCP, unprocessed
    • “udp”: UDP
    • “win-event-log-collections”: Windows event log
    • “win-perfmon”: Performance monitoring
    • “win-wmi-collections”: WMI
  • kwargs (dict) –

    Additional arguments (optional). For more about the available parameters, see Input parameters on Splunk Developer Portal.

Returns:

The new Input.

delete(name, kind=None)

Removes an input from the collection.

Parameters:
  • kind (string) –

    The kind of input:

    • “ad”: Active Directory
    • “monitor”: Files and directories
    • “registry”: Windows Registry
    • “script”: Scripts
    • “splunktcp”: TCP, processed
    • “tcp”: TCP, unprocessed
    • “udp”: UDP
    • “win-event-log-collections”: Windows event log
    • “win-perfmon”: Performance monitoring
    • “win-wmi-collections”: WMI
  • name (string) – The name of the input to remove.
Returns:

The Inputs collection.

get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta(kind)

Returns metadata for the members of a given kind.

Parameters:kind (string) –

The kind of input:

  • “ad”: Active Directory
  • “monitor”: Files and directories
  • “registry”: Windows Registry
  • “script”: Scripts
  • “splunktcp”: TCP, processed
  • “tcp”: TCP, unprocessed
  • “udp”: UDP
  • “win-event-log-collections”: Windows event log
  • “win-perfmon”: Performance monitoring
  • “win-wmi-collections”: WMI
Returns:The metadata.
Return type:class:splunklib.data.Record
iter(**kwargs)

Iterates over the collection of inputs.

Parameters:kwargs (dict) –

Additional arguments (optional):

  • “count” (integer): The maximum number of items to return.
  • “offset” (integer): The offset of the first item to return.
  • “search” (string): The search query to filter responses.
  • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
  • “sort_key” (string): The field to use for sorting (optional).
  • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
kindpath(kind)

Returns a path to the resources for a given input kind.

Parameters:kind (string) –

The kind of input:

  • “ad”: Active Directory
  • “monitor”: Files and directories
  • “registry”: Windows Registry
  • “script”: Scripts
  • “splunktcp”: TCP, processed
  • “tcp”: TCP, unprocessed
  • “udp”: UDP
  • “win-event-log-collections”: Windows event log
  • “win-perfmon”: Performance monitoring
  • “win-wmi-collections”: WMI
Returns:The relative endpoint path.
Return type:string
kinds

Returns the input kinds on this Splunk instance.

Returns:The list of input kinds.
Return type:list
list(*kinds, **kwargs)

Returns a list of inputs that are in the Inputs collection. You can also filter by one or more input kinds.

This function iterates over all possible inputs, regardless of any arguments you specify. Because the Inputs collection is the union of all the inputs of each kind, this method implements parameters such as “count”, “search”, and so on at the Python level once all the data has been fetched. The exception is when you specify a single input kind, and then this method makes a single request with the usual semantics for parameters.

Parameters:
  • kinds (string) –

    The input kinds to return (optional).

    • “ad”: Active Directory
    • “monitor”: Files and directories
    • “registry”: Windows Registry
    • “script”: Scripts
    • “splunktcp”: TCP, processed
    • “tcp”: TCP, unprocessed
    • “udp”: UDP
    • “win-event-log-collections”: Windows event log
    • “win-perfmon”: Performance monitoring
    • “win-wmi-collections”: WMI
  • kwargs (dict) –

    Additional arguments (optional):

    • “count” (integer): The maximum number of items to return.
    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of input kinds.

Return type:

list

oneshot(path, **kwargs)

Creates a oneshot data input, which is an upload of a single file for one-time indexing.

Parameters:
  • path (string) – The path and filename.
  • kwargs (dict) –

    Additional arguments (optional). For more about the available parameters, see Input parameters on Splunk Developer Portal.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.InvalidNameException

Thrown when the specified name contains characters that are not allowed in Splunk entity names.

class splunklib.client.Job(service, sid, **kwargs)

This class represents a search job.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
cancel()

Stops the current search and deletes the results cache.

Returns:The Job.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

disable_preview()

Disables preview for this job.

Returns:The Job.
enable()

Enables the entity at this endpoint.

enable_preview()

Enables preview for this job.

Note: Enabling preview might slow search considerably.

Returns:The Job.
events(**kwargs)

Returns a streaming handle to this job’s events.

Parameters:kwargs (dict) – Additional parameters (optional). For a list of valid parameters, see GET search/jobs/{search_id}/events in the REST API documentation.
Returns:The InputStream IO handle to this job’s events.
fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.
finalize()

Stops the job and provides intermediate results for retrieval.

Returns:The Job.
is_done()

Indicates whether this job finished running.

Returns:True if the job is done, False if not.
Return type:boolean
is_ready()

Indicates whether this job is ready for querying.

Returns:True if the job is ready, False if not.
Return type:boolean

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the name of the search job, which is the search ID (SID).

Returns:The search ID.
Return type:string
pause()

Suspends the current search.

Returns:The Job.
preview(**query_params)

Returns a streaming handle to this job’s preview search results.

Unlike splunklib.results.ResultsReader, which requires a job to be finished to return any results, the preview method returns any results that have been generated so far, whether the job is running or not. The returned search results are the raw data from the server. Pass the handle returned to splunklib.results.ResultsReader to get a nice, Pythonic iterator over objects, as in:

import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
job = service.jobs.create("search * | head 5")
rr = results.ResultsReader(job.preview())
for result in rr:
    if isinstance(result, results.Message):
        # Diagnostic messages may be returned in the results
        print '%s: %s' % (result.type, result.message)
    elif isinstance(result, dict):
        # Normal events are returned as dicts
        print result
if rr.is_preview:
    print "Preview of a running search job."
else:
    print "Job is finished. Results are final."

This method makes one roundtrip to the server, plus at most two more if the autologin field of connect() is set to True.

Parameters:query_params (dict) – Additional parameters (optional). For a list of valid parameters, see GET search/jobs/{search_id}/results_preview in the REST API documentation.
Returns:The InputStream IO handle to this job’s preview results.
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

results(**query_params)

Returns a streaming handle to this job’s search results. To get a nice, Pythonic iterator, pass the handle to splunklib.results.ResultsReader, as in:

import splunklib.client as client
import splunklib.results as results
from time import sleep
service = client.connect(...)
job = service.jobs.create("search * | head 5")
while not job.is_done():
    sleep(.2)
rr = results.ResultsReader(job.results())
for result in rr:
    if isinstance(result, results.Message):
        # Diagnostic messages may be returned in the results
        print '%s: %s' % (result.type, result.message)
    elif isinstance(result, dict):
        # Normal events are returned as dicts
        print result
assert rr.is_preview == False

Results are not available until the job has finished. If called on an unfinished job, the result is an empty event set.

This method makes a single roundtrip to the server, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:query_params (dict) – Additional parameters (optional). For a list of valid parameters, see GET search/jobs/{search_id}/results.
Returns:The InputStream IO handle to this job’s results.
searchlog(**kwargs)

Returns a streaming handle to this job’s search log.

Parameters:kwargs (dict) – Additional parameters (optional). For a list of valid parameters, see GET search/jobs/{search_id}/search.log in the REST API documentation.
Returns:The InputStream IO handle to this job’s search log.
set_priority(value)

Sets this job’s search priority in the range of 0-10.

Higher numbers indicate higher priority. Unless splunkd is running as root, you can only decrease the priority of a running job.

Parameters:value (integer) – The search priority.
Returns:The Job.
set_ttl(value)

Set the job’s time-to-live (ttl) value, which is the time before the search job expires and is still available.

Parameters:value (integer) – The ttl value, in seconds.
Returns:The Job.
state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
summary(**kwargs)

Returns a streaming handle to this job’s summary.

Parameters:kwargs (dict) – Additional parameters (optional). For a list of valid parameters, see GET search/jobs/{search_id}/summary in the REST API documentation.
Returns:The InputStream IO handle to this job’s summary.
timeline(**kwargs)

Returns a streaming handle to this job’s timeline results.

Parameters:kwargs (dict) – Additional timeline arguments (optional). For a list of valid parameters, see GET search/jobs/{search_id}/timeline in the REST API documentation.
Returns:The InputStream IO handle to this job’s timeline.
touch()

Extends the expiration time of the search to the current time (now) plus the time-to-live (ttl) value.

Returns:The Job.
unpause()

Resumes the current search, if paused.

Returns:The Job.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
class splunklib.client.Jobs(service)

This class represents a collection of search jobs. Retrieve this collection using Service.jobs().

create(query, **kwargs)

Creates a search using a search query and any additional parameters you provide.

Parameters:
  • query (string) – The search query.
  • kwargs (dict) – Additiona parameters (optional). For a list of available parameters, see Search job parameters on Splunk Developer Portal.
Returns:

The Job.

delete(name, **params)

Deletes a specified entity from the collection.

Parameters:name (string) – The name of the entity to delete.
Returns:The collection.
Return type:self

This method is implemented for consistency with the REST API’s DELETE method.

If there is no name entity on the server, a KeyError is thrown. This function always makes a roundtrip to the server.

Example:

import splunklib.client as client
c = client.connect(...)
saved_searches = c.saved_searches
saved_searches.create('my_saved_search',
                      'search * | head 1')
assert 'my_saved_search' in saved_searches
saved_searches.delete('my_saved_search')
assert 'my_saved_search' not in saved_searches
export(query, **params)

Runs a search and immediately starts streaming preview events. This method returns a streaming handle to this job’s events as an XML document from the server. To parse this stream into usable Python objects, pass the handle to splunklib.results.ResultsReader:

import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
rr = results.ResultsReader(service.jobs.export("search * | head 5"))
for result in rr:
    if isinstance(result, results.Message):
        # Diagnostic messages may be returned in the results
        print '%s: %s' % (result.type, result.message)
    elif isinstance(result, dict):
        # Normal events are returned as dicts
        print result
assert rr.is_preview == False

Running an export search is more efficient than running a similar preview search because no post-processing is done on the retrieved events. The raw events are simply returned.

The export method makes a single roundtrip to the server (as opposed to two for create() followed by preview()), plus at most two more if the autologin field of connect() is set to True.

Raises ValueError:
 

Raised for invalid queries.

Parameters:
  • query (string) – The search query.
  • params (dict) – Additional arguments (optional). For a list of valid parameters, see GET search/jobs/export in the REST API documentation.
Returns:

The InputStream IO handle to raw XML returned from the server.

get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

There is no metadata available for class:Jobs.

Any call to this method raises a class:NotSupportedError.

Raises :class:NotSupportedError
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

oneshot(query, **params)

Run a oneshot search and returns a streaming handle to the results.

The InputStream object streams XML fragments from the server. To parse this stream into usable Python objects, pass the handle to splunklib.results.ResultsReader:

import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
rr = results.ResultsReader(service.jobs.oneshot("search * | head 5"))
for result in rr:
    if isinstance(result, results.Message):
        # Diagnostic messages may be returned in the results
        print '%s: %s' % (result.type, result.message)
    elif isinstance(result, dict):
        # Normal events are returned as dicts
        print result
assert rr.is_preview == False

The oneshot method makes a single roundtrip to the server (as opposed to two for create() followed by results()), plus at most two more if the autologin field of connect() is set to True.

Raises ValueError:
 

Raised for invalid queries.

Parameters:
  • query (string) – The search query.
  • params (dict) –

    Additional arguments (optional):

    • “output_mode”: Specifies the output format of the results (XML, JSON, or CSV).
    • “earliest_time”: Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
    • “latest_time”: Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
    • “rf”: Specifies one or more fields to add to the search.
Returns:

The InputStream IO handle to raw XML returned from the server.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Loggers(service)

This class represents a collection of service logging categories. Retrieve this collection using Service.loggers().

create(name, **params)

Creates a new entity in this collection.

This function makes either one or two roundtrips to the server, depending on the type of entities in this collection, plus at most two more if the autologin field of connect() is set to True.

Parameters:
  • name (string) – The name of the entity to create.
  • namespace (A splunklib.data.Record object with keys owner, app, and sharing.) – A namespace, as created by the splunklib.binding.namespace() function (optional). You can also set owner, app, and sharing in params.
  • params (dict) – Additional entity-specific arguments (optional).
Returns:

The new entity.

Return type:

A subclass of Entity, chosen by Collection.self.item().

Example:

import splunklib.client as client
s = client.connect(...)
applications = s.apps
new_app = applications.create("my_fake_app")
delete(name, **params)

Deletes a specified entity from the collection.

Parameters:name (string) – The name of the entity to delete.
Returns:The collection.
Return type:self

This method is implemented for consistency with the REST API’s DELETE method.

If there is no name entity on the server, a KeyError is thrown. This function always makes a roundtrip to the server.

Example:

import splunklib.client as client
c = client.connect(...)
saved_searches = c.saved_searches
saved_searches.create('my_saved_search',
                      'search * | head 1')
assert 'my_saved_search' in saved_searches
saved_searches.delete('my_saved_search')
assert 'my_saved_search' not in saved_searches
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

There is no metadata available for class:Loggers.

Any call to this method raises a class:NotSupportedError.

Raises :class:NotSupportedError
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Message(service, path, **kwargs)
access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
value

Returns the message value.

Returns:The Loggers collection.
class splunklib.client.ModularInputKind(service, path, **kwargs)

This class contains the different types of modular inputs. Retrieve this collection using Service.modular_input_kinds().

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
arguments

A dictionary of all the arguments supported by this modular input kind.

The keys in the dictionary are the names of the arguments. The values are another dictionary giving the metadata about that argument. The possible keys in that dictionary are "title", "description", "required_on_create”, "required_on_edit", "data_type". Each value is a string. It should be one of "true" or "false" for "required_on_create" and "required_on_edit", and one of "boolean", "string", or "number” for "data_type".

Returns:A dictionary describing the arguments this modular input kind takes.
Return type:dict
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Raises an error. Modular input kinds are read only.

class splunklib.client.NoSuchCapability

Thrown when the capability that has been referred to doesn’t exist.

class splunklib.client.NotSupportedError

Raised for operations that are not supported on a given object.

class splunklib.client.OperationError

Raised for a failed operation, such as a time out.

class splunklib.client.ReadOnlyCollection(service, path, item=<class 'splunklib.client.Entity'>)

This class represents a read-only collection of entities in the Splunk instance.

get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Role(service, path, **kwargs)

This class represents a user role.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.
grant(*capabilities_to_grant)

Grants additional capabilities to this role.

Parameters:capabilities_to_grant (string or list) – Zero or more capabilities to grant this role. For a list of capabilities, see Capabilities on Splunk Developer Portal.
Returns:The Role.

Example:

service = client.connect(...)
role = service.roles['somerole']
role.grant('change_own_password', 'search')

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

revoke(*capabilities_to_revoke)

Revokes zero or more capabilities from this role.

Parameters:capabilities_to_revoke (string or list) –

Zero or more capabilities to grant this role. For a list of capabilities, see Capabilities on Splunk Developer Portal.

Returns:The Role.

Example:

service = client.connect(...)
role = service.roles['somerole']
role.revoke('change_own_password', 'search')
state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
class splunklib.client.Roles(service)

This class represents the collection of roles in the Splunk instance. Retrieve this collection using Service.roles().

create(name, **params)

Creates a new role.

This function makes two roundtrips to the server, plus at most two more if the autologin field of connect() is set to True.

Parameters:
  • name (string) – Name for the role.
  • params (dict) – Additional arguments (optional). For a list of available parameters, see Roles parameters on Splunk Developer Portal.
Returns:

The new role.

Return type:

Role

Example:

import splunklib.client as client
c = client.connect(...)
roles = c.roles
paltry = roles.create("paltry", imported_roles="user", defaultApp="search")
delete(name)

Deletes the role and returns the resulting collection of roles.

Parameters:name (string) – The name of the role to delete.
Return type:The Roles
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.SavedSearch(service, path, **kwargs)

This class represents a saved search.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
acknowledge()

Acknowledges the suppression of alerts from this saved search and resumes alerting.

Returns:The SavedSearch.
alert_count

Returns the number of alerts fired by this saved search.

Returns:The number of alerts fired by this saved search.
Return type:integer
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

dispatch(**kwargs)

Runs the saved search and returns the resulting search job.

Parameters:kwargs (dict) – Additional dispatch arguments (optional). For details, see the POST saved/searches/{name}/dispatch endpoint in the REST API documentation.
Returns:The Job.
enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.
fired_alerts

Returns the collection of fired alerts (a fired alert group) corresponding to this saved search’s alerts.

Raises IllegalOperationException:
 Raised when the search is not scheduled.
Returns:A collection of fired alerts.
Return type:AlertGroup
history()

Returns a list of search jobs corresponding to this saved search.

Returns:A list of Job objects.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

scheduled_times(earliest_time='now', latest_time='+1h')

Returns the times when this search is scheduled to run.

By default this method returns the times in the next hour. For different time ranges, set earliest_time and latest_time. For example, for all times in the last day use “earliest_time=-1d” and “latest_time=now”.

Parameters:
  • earliest_time (string) – The earliest time.
  • latest_time (string) – The latest time.
Returns:

The list of search times.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
suppress(expiration)

Skips any scheduled runs of this search in the next expiration number of seconds.

Parameters:expiration (integer) – The expiration period, in seconds.
Returns:The SavedSearch.
suppressed

Returns the number of seconds that this search is blocked from running (possibly 0).

Returns:The number of seconds.
Return type:integer
unsuppress()

Cancels suppression and makes this search run as scheduled.

Returns:The SavedSearch.
update(search=None, **kwargs)

Updates the server with any changes you’ve made to the current saved search along with any additional arguments you specify.

Parameters:
  • search (string) – The search query (optional).
  • kwargs (dict) – Additional arguments (optional). For a list of available parameters, see Saved search parameters on Splunk Developer Portal.
Returns:

The SavedSearch.

class splunklib.client.SavedSearches(service)

This class represents a collection of saved searches. Retrieve this collection using Service.saved_searches().

create(name, search, **kwargs)

Creates a saved search.

Parameters:
  • name (string) – The name for the saved search.
  • search (string) – The search query.
  • kwargs (dict) –

    Additional arguments (optional). For a list of available parameters, see Saved search parameters on Splunk Developer Portal.

Returns:

The SavedSearches collection.

delete(name, **params)

Deletes a specified entity from the collection.

Parameters:name (string) – The name of the entity to delete.
Returns:The collection.
Return type:self

This method is implemented for consistency with the REST API’s DELETE method.

If there is no name entity on the server, a KeyError is thrown. This function always makes a roundtrip to the server.

Example:

import splunklib.client as client
c = client.connect(...)
saved_searches = c.saved_searches
saved_searches.create('my_saved_search',
                      'search * | head 1')
assert 'my_saved_search' in saved_searches
saved_searches.delete('my_saved_search')
assert 'my_saved_search' not in saved_searches
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
class splunklib.client.Service(**kwargs)

A Pythonic binding to Splunk instances.

A Service represents a binding to a Splunk instane on an HTTP or HTTPS port. It handles the details of authentication, wire formats, and wraps the REST API endpoints into something more Pythonic. All of the low-level operations on the instance from splunklib.binding.Context are also available in case you need to do something beyond what is provided by this class.

After creating a Service object, you must call its login() method before you can issue requests to Splunk. Alternately, use the connect() function to create an already authenticated Service object, or provide a session token when creating the Service object explicitly (the same token may be shared by multiple Service objects).

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 (optional; use “-” for wildcard).
  • app (string) – The app context of the namespace (optional; use “-” for wildcard).
  • token (string) – The current session token (optional). Session tokens can be shared across multiple service instances.
  • username (string) – The Splunk account username, which is used to authenticate the Splunk instance.
  • password (string) – The password, which is used to authenticate the Splunk instance.
Returns:

A Service instance.

Example:

import splunklib.client as client
s = client.Service(username="boris", password="natasha", ...)
s.login()
# Or equivalently
s = client.connect(username="boris", password="natasha")
# Or if you already have a session token
s = client.Service(token="atg232342aa34324a")
apps

Returns the collection of applications that are installed on this instance of Splunk.

Returns:A Collection of Application entities.
capabilities

Returns the list of system capabilities.

Returns:A list of capabilities.
confs

Returns the collection of configuration files for this Splunk instance.

Returns:A Configurations collection of ConfigurationFile entities.
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(*args, **kwargs)

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
event_types

Returns the collection of event types defined in this Splunk instance.

Returns:An Entity containing the event types.
fired_alerts

Returns the collection of alerts that have been fired on the Splunk instance, grouped by saved search.

Returns:A Collection of AlertGroup entities.
get(*args, **kwargs)

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).
  • 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
indexes

Returns the collection of indexes for this Splunk instance.

Returns:An Indexes collection of Index entities.
info

Returns the information about this instance of Splunk.

Returns:The system information, as key-value pairs.
Return type:dict
inputs

Returns the collection of inputs configured on this Splunk instance.

Returns:An Inputs collection of Input entities.
jobs

Returns the collection of current search jobs.

Returns:A Jobs collection of Job entities.
loggers

Returns the collection of logging level categories and their status.

Returns:A Loggers collection of logging levels.
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.

messages

Returns the collection of service messages.

Returns:A Collection of Message entities.
modular_input_kinds

Returns the collection of the modular input kinds on this Splunk instance.

Returns:A ReadOnlyCollection of ModularInputKind entities.
parse(query, **kwargs)

Parses a search query and returns a semantic map of the search.

Parameters:
  • query (string) – The search query to parse.
  • kwargs (dict) –

    Arguments to pass to the search/parser endpoint (optional). Valid arguments are:

    • “enable_lookups” (boolean): If True, performs reverse lookups to expand the search expression.
    • “output_mode” (string): The output format (XML or JSON).
    • “parse_only” (boolean): If True, disables the expansion of search due to evaluation of subsearches, time term expansion, lookups, tags, eventtypes, and sourcetype alias.
    • “reload_macros” (boolean): If True, reloads macro definitions from macros.conf.
Returns:

A semantic map of the parsed search query.

post(*args, **kwargs)

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 (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.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(*args, **kwargs)

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).
  • 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.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
restart(timeout=None)

Restarts this Splunk instance.

The service is unavailable until it has successfully restarted.

If a timeout value is specified, restart blocks until the service resumes or the timeout period has been exceeded. Otherwise, restart returns immediately.

Parameters:timeout (integer) – A timeout period, in seconds.
restart_required

Indicates whether splunkd is in a state that requires a restart.

Returns:A boolean that indicates whether a restart is required.
roles

Returns the collection of user roles.

Returns:A Roles collection of Role entities.
saved_searches

Returns the collection of saved searches.

Returns:A SavedSearches collection of SavedSearch entities.
search(query, **kwargs)

Runs a search using a search query and any optional arguments you provide, and returns a Job object representing the search.

Parameters:
  • query (string) – A search query.
  • kwargs (dict) –

    Arguments for the search (optional):

    • “output_mode” (string): Specifies the output format of the results.
    • “earliest_time” (string): Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
    • “latest_time” (string): Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
    • “rf” (string): Specifies one or more fields to add to the search.
Return type:

class:Job

Returns:

An object representing the created job.

settings

Returns the configuration settings for this instance of Splunk.

Returns:A Settings object containing configuration settings.
splunk_version

Returns the version of the splunkd instance this object is attached to.

The version is returned as a tuple of the version components as integers (for example, (4,3,3) or (5,)).

Returns:A tuple of integers.
users

Returns the collection of users.

Returns:A Users collection of User entities.
class splunklib.client.Settings(service, **kwargs)

This class represents configuration settings for a Splunk service. Retrieve this collection using Service.settings().

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the settings on the server using the arguments you provide.

Parameters:kwargs (dict) – Additional arguments. For a list of valid arguments, see POST server/settings/{name} in the REST API documentation.
Returns:The Settings collection.
class splunklib.client.Stanza(service, path, **kwargs)

This class contains a single configuration stanza.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
submit(stanza)

Adds keys to the current configuration stanza as a dictionary of key-value pairs.

Parameters:stanza (dict) – A dictionary of key-value pairs for the stanza.
Returns:The Stanza object.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
class splunklib.client.User(service, path, **kwargs)

This class represents a Splunk user.

access

Returns the access metadata for this entity.

Returns:A splunklib.data.Record object with three keys: owner, app, and sharing.
content

Returns the contents of the entity.

Returns:A dict containing values.
disable()

Disables the entity at this endpoint.

enable()

Enables the entity at this endpoint.

fields

Returns the content metadata for this entity.

Returns:A splunklib.data.Record object with three keys: required, optional, and wildcard.

Returns a dictionary of related resources.

Returns:A dict with keys and corresponding URLs.
name

Returns the entity name.

Returns:The entity name.
Return type:string
read()

Reads the current state of the entity from the server.

refresh(state=None)

Refreshes the state of this entity.

If state is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the read() method of self) to fetch an updated state, plus at most two additional round trips if the autologin field of connect() is set to True.

Parameters:state (dict) – Entity-specific arguments (optional).
Raises EntityDeletedException:
 Raised if the entity no longer exists on the server.

Example:

import splunklib.client as client
s = client.connect(...)
search = s.apps['search']
search.refresh()
reload()

Reloads the entity.

role_entities

Returns a list of roles assigned to this user.

Returns:The list of roles.
Return type:list
state

Returns the entity’s state record.

Returns:A dict containing fields and metadata for the entity.
update(**kwargs)

Updates the server with any changes you’ve made to the current entity along with any additional arguments you specify.

Note: You cannot update the name field of an entity.

Many of the fields in the REST API are not valid Python identifiers, which means you cannot pass them as keyword arguments. That is, Python will fail to parse the following:

# This fails
x.update(check-new=False, email.to='boris@utopia.net')

However, you can always explicitly use a dictionary to pass such keys:

# This works
x.update(**{'check-new': False, 'email.to': 'boris@utopia.net'})
Parameters:kwargs (dict) – Additional entity-specific arguments (optional).
Returns:The entity this method is called on.
Return type:class:Entity
class splunklib.client.Users(service)

This class represents the collection of Splunk users for this instance of Splunk. Retrieve this collection using Service.users().

create(username, password, roles, **params)

Creates a new user.

This function makes two roundtrips to the server, plus at most two more if the autologin field of connect() is set to True.

Parameters:
  • username (string) – The username.
  • password (string) – The password.
  • roles (string or list) – A single role or list of roles for the user.
  • params (dict) – Additional arguments (optional). For a list of available parameters, see User authentication parameters on Splunk Developer Portal.
Returns:

The new user.

Return type:

User

Example:

import splunklib.client as client
c = client.connect(...)
users = c.users
boris = users.create("boris", "securepassword", roles="user")
hilda = users.create("hilda", "anotherpassword", roles=["user","power"])
delete(name)

Deletes the user and returns the resulting collection of users.

Parameters:name (string) – The name of the user to delete.
Returns:
Return type:Users
get(path_segment='', owner=None, app=None, sharing=None, **query)

Performs a GET operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • owner (string) – The owner context of the namespace (optional).
  • app (string) – The app context of the namespace (optional).
  • sharing (“global”, “system”, “app”, or “user”) – The sharing mode for 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.get() == \
    {'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}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError
itemmeta()

Returns metadata for members of the collection.

Makes a single roundtrip to the server, plus two more at most if the autologin field of connect() is set to True.

Returns:A splunklib.data.Record object containing the metadata.

Example:

import splunklib.client as client
import pprint
s = client.connect(...)
pprint.pprint(s.apps.itemmeta())
{'access': {'app': 'search',
                        'can_change_perms': '1',
                        'can_list': '1',
                        'can_share_app': '1',
                        'can_share_global': '1',
                        'can_share_user': '1',
                        'can_write': '1',
                        'modifiable': '1',
                        'owner': 'admin',
                        'perms': {'read': ['*'], 'write': ['admin']},
                        'removable': '0',
                        'sharing': 'user'},
 'fields': {'optional': ['author',
                            'configured',
                            'description',
                            'label',
                            'manageable',
                            'template',
                            'visible'],
                            'required': ['name'], 'wildcard': []}}
iter(offset=0, count=None, pagesize=None, **kwargs)

Iterates over the collection.

This method is equivalent to the list() method, but it returns an iterator and can load a certain number of entities at a time from the server.

Parameters:
  • offset (integer) – The index of the first entity to return (optional).
  • count (integer) – The maximum number of entities to return (optional).
  • pagesize (integer) – The number of entities to load (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.

Example:

import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
    # Loads 10 saved searches at a time from the
    # server.
    ...
list(count=None, **kwargs)

Retrieves a list of entities in this collection.

The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the autologin field of connect() is set to True. There is no caching–every call makes at least one round trip.

Parameters:
  • count (integer) – The maximum number of entities to return (optional).
  • kwargs (dict) –

    Additional arguments (optional):

    • “offset” (integer): The offset of the first item to return.
    • “search” (string): The search query to filter responses.
    • “sort_dir” (string): The direction to sort returned items: “asc” or “desc”.
    • “sort_key” (string): The field to use for sorting (optional).
    • “sort_mode” (string): The collating sequence for sorting returned items: “auto”, “alpha”, “alpha_case”, or “num”.
Returns:

A list of entities.

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

Performs a POST operation on the path segment relative to this endpoint.

This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus 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 takes a default namespace from the Service object for this Endpoint. All other keyword arguments are included in the URL as query parameters.

Raises:
  • AuthenticationError – Raised when the Service is not logged in.
  • HTTPError – Raised when an error in the request occurs.
Parameters:
  • path_segment (string) – A path segment relative to this endpoint.
  • 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:

import splunklib.client
s = client.service(...)
apps = s.apps
apps.post(name='boris') == \
    {'body': '...a response reader object...',
     'headers': [('content-length', '2908'),
                 ('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 18:34:50 GMT'),
                 ('content-type', 'text/xml; charset=utf-8')],
     'reason': 'Created',
     'status': 201}
apps.get('nonexistant/path') # raises HTTPError
s.logout()
apps.get() # raises AuthenticationError