本文整理汇总了Python中splunklib.binding.Context方法的典型用法代码示例。如果您正苦于以下问题:Python binding.Context方法的具体用法?Python binding.Context怎么用?Python binding.Context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类splunklib.binding
的用法示例。
在下文中一共展示了binding.Context方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _auth_headers
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def _auth_headers(self):
"""Headers required to authenticate a request.
Assumes your ``Context`` already has a authentication token or
cookie, either provided explicitly or obtained by logging
into the Splunk instance.
:returns: A list of 2-tuples containing key and value
"""
if self.has_cookies():
return [("Cookie", _make_cookie_header(list(self.get_cookies().items())))]
elif self.basic and (self.username and self.password):
token = 'Basic %s' % b64encode(("%s:%s" % (self.username, self.password)).encode('utf-8')).decode('ascii')
return [("Authorization", token)]
elif self.token is _NoAuthenticationToken:
return []
else:
# Ensure the token is properly formatted
if self.token.startswith('Splunk '):
token = self.token
else:
token = 'Splunk %s' % self.token
return [("Authorization", token)]
示例2: _auth_headers
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def _auth_headers(self):
"""Headers required to authenticate a request.
Assumes your ``Context`` already has a authentication token or
cookie, either provided explicitly or obtained by logging
into the Splunk instance.
:returns: A list of 2-tuples containing key and value
"""
if self.has_cookies():
return [("Cookie", _make_cookie_header(self.get_cookies().items()))]
elif self.token is _NoAuthenticationToken:
return []
else:
# Ensure the token is properly formatted
if self.token.startswith('Splunk '):
token = self.token
else:
token = 'Splunk %s' % self.token
return [("Authorization", token)]
示例3: _auth_headers
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def _auth_headers(self):
"""Headers required to authenticate a request.
Assumes your ``Context`` already has a authentication token,
either provided explicitly or obtained by logging into the
Splunk instance.
:returns: A list of 2-tuples containing key and value
"""
if self.token is _NoAuthenticationToken:
return []
else:
# Ensure the token is properly formatted
if self.token.startswith('Splunk '):
token = self.token
else:
token = 'Splunk %s' % self.token
return [("Authorization", token)]
示例4: _auth_headers
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def _auth_headers(self):
"""Headers required to authenticate a request.
Assumes your ``Context`` already has a authentication token or
cookie, either provided explicitly or obtained by logging
into the Splunk instance.
:returns: A list of 2-tuples containing key and value
"""
if self.has_cookies():
return [("Cookie", _make_cookie_header(self.get_cookies().items()))]
elif self.basic and (self.username and self.password):
token = 'Basic %s' % b64encode("%s:%s" % (self.username, self.password))
return [("Authorization", token)]
elif self.token is _NoAuthenticationToken:
return []
else:
# Ensure the token is properly formatted
if self.token.startswith('Splunk '):
token = self.token
else:
token = 'Splunk %s' % self.token
return [("Authorization", token)]
示例5: _auth_headers
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def _auth_headers(self):
"""Headers required to authenticate a request.
Assumes your ``Context`` already has a authentication token or
cookie, either provided explicitly or obtained by logging
into the Splunk instance.
:returns: A list of 2-tuples containing key and value
"""
if self.has_cookies():
return [("Cookie", _make_cookie_header(list(self.get_cookies().items())))]
elif self.basic and (self.username and self.password):
token = 'Basic %s' % b64encode(("%s:%s" % (self.username, self.password)).encode('utf-8')).decode('ascii')
return [("Authorization", token)]
elif self.bearerToken:
token = 'Bearer %s' % self.bearerToken
return [("Authorization", token)]
elif self.token is _NoAuthenticationToken:
return []
else:
# Ensure the token is properly formatted
if self.token.startswith('Splunk '):
token = self.token
else:
token = 'Splunk %s' % self.token
return [("Authorization", token)]
示例6: login
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def login(self):
"""Logs into the Splunk instance referred to by the :class:`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 :meth:`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...
"""
if self.token is not _NoAuthenticationToken and \
(not self.username and not self.password):
# If we were passed a session token, but no username or
# password, then login is a nop, since we're automatically
# logged in.
return
try:
response = self.http.post(
self.authority + self._abspath("/services/auth/login"),
username=self.username,
password=self.password)
body = response.body.read()
session = XML(body).findtext("./sessionKey")
self.token = "Splunk %s" % session
return self
except HTTPError as he:
if he.status == 401:
raise AuthenticationError("Login failed.", he)
else:
raise
示例7: delete
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
"""Performs a DELETE operation at the REST path segment with the given
namespace and query.
This method is named to match the HTTP method. ``delete`` makes at least
one round trip to the server, one additional round trip for each 303
status returned, and at most two additional round trips if
the ``autologin`` field of :func:`connect` is set to ``True``.
If *owner*, *app*, and *sharing* are omitted, this method uses the
default :class:`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.
:raises HTTPError: Raised when an error occurred in a GET operation from
*path_segment*.
:param path_segment: A REST path segment.
:type path_segment: ``string``
:param owner: The owner context of the namespace (optional).
:type owner: ``string``
:param app: The app context of the namespace (optional).
:type app: ``string``
:param sharing: The sharing mode of the namespace (optional).
:type sharing: ``string``
:param query: All other keyword arguments, which are used as query
parameters.
:type query: ``string``
:return: The response from the server.
:rtype: ``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
"""
path = self.authority + self._abspath(path_segment, owner=owner,
app=app, sharing=sharing)
logging.debug("DELETE request to %s (body: %s)", path, repr(query))
response = self.http.delete(path, self._auth_headers, **query)
return response
示例8: get
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def get(self, path_segment, owner=None, app=None, headers=None, sharing=None, **query):
"""Performs a GET operation from the REST path segment with the given
namespace and query.
This method is named to match the HTTP method. ``get`` makes at least
one round trip to the server, one additional round trip for each 303
status returned, and at most two additional round trips if
the ``autologin`` field of :func:`connect` is set to ``True``.
If *owner*, *app*, and *sharing* are omitted, this method uses the
default :class:`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.
:raises HTTPError: Raised when an error occurred in a GET operation from
*path_segment*.
:param path_segment: A REST path segment.
:type path_segment: ``string``
:param owner: The owner context of the namespace (optional).
:type owner: ``string``
:param app: The app context of the namespace (optional).
:type app: ``string``
:param headers: List of extra HTTP headers to send (optional).
:type headers: ``list`` of 2-tuples.
:param sharing: The sharing mode of the namespace (optional).
:type sharing: ``string``
:param query: All other keyword arguments, which are used as query
parameters.
:type query: ``string``
:return: The response from the server.
:rtype: ``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
"""
if headers is None:
headers = []
path = self.authority + self._abspath(path_segment, owner=owner,
app=app, sharing=sharing)
logging.debug("GET request to %s (body: %s)", path, repr(query))
all_headers = headers + self.additional_headers + self._auth_headers
response = self.http.get(path, all_headers, **query)
return response
示例9: login
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def login(self):
"""Logs into the Splunk instance referred to by the :class:`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 :meth:`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...
"""
if self.has_cookies() and \
(not self.username and not self.password):
# If we were passed session cookie(s), but no username or
# password, then login is a nop, since we're automatically
# logged in.
return
if self.token is not _NoAuthenticationToken and \
(not self.username and not self.password):
# If we were passed a session token, but no username or
# password, then login is a nop, since we're automatically
# logged in.
return
if self.basic and (self.username and self.password):
# Basic auth mode requested, so this method is a nop as long
# as credentials were passed in.
return
if self.bearerToken:
# Bearer auth mode requested, so this method is a nop as long
# as authentication token was passed in.
return
# Only try to get a token and updated cookie if username & password are specified
try:
response = self.http.post(
self.authority + self._abspath("/services/auth/login"),
username=self.username,
password=self.password,
headers=self.additional_headers,
cookie="1") # In Splunk 6.2+, passing "cookie=1" will return the "set-cookie" header
body = response.body.read()
session = XML(body).findtext("./sessionKey")
self.token = "Splunk %s" % session
return self
except HTTPError as he:
if he.status == 401:
raise AuthenticationError("Login failed.", he)
else:
raise
示例10: _abspath
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def _abspath(self, path_segment,
owner=None, app=None, sharing=None):
"""Qualifies *path_segment* into an absolute path for a URL.
If *path_segment* is already absolute, returns it unchanged.
If *path_segment* is relative, then qualifies it with either
the provided namespace arguments or the ``Context``'s default
namespace. Any forbidden characters in *path_segment* are URL
encoded. This function has no network activity.
Named to be consistent with RFC2396_.
.. _RFC2396: http://www.ietf.org/rfc/rfc2396.txt
:param path_segment: A relative or absolute URL path segment.
:type path_segment: ``string``
:param owner, app, sharing: Components of a namespace (defaults
to the ``Context``'s namespace if all
three are omitted)
:type owner, app, sharing: ``string``
:return: A ``UrlEncoded`` (a subclass of ``str``).
:rtype: ``string``
**Example**::
import splunklib.binding as binding
c = binding.connect(owner='boris', app='search', sharing='user')
c._abspath('/a/b/c') == '/a/b/c'
c._abspath('/a/b c/d') == '/a/b%20c/d'
c._abspath('apps/local/search') == \
'/servicesNS/boris/search/apps/local/search'
c._abspath('apps/local/search', sharing='system') == \
'/servicesNS/nobody/system/apps/local/search'
url = c.authority + c._abspath('apps/local/sharing')
"""
skip_encode = isinstance(path_segment, UrlEncoded)
# If path_segment is absolute, escape all forbidden characters
# in it and return it.
if path_segment.startswith('/'):
return UrlEncoded(path_segment, skip_encode=skip_encode)
# path_segment is relative, so we need a namespace to build an
# absolute path.
if owner or app or sharing:
ns = namespace(owner=owner, app=app, sharing=sharing)
else:
ns = self.namespace
# If no app or owner are specified, then use the /services
# endpoint. Otherwise, use /servicesNS with the specified
# namespace. If only one of app and owner is specified, use
# '-' for the other.
if ns.app is None and ns.owner is None:
return UrlEncoded("/services/%s" % path_segment, skip_encode=skip_encode)
oname = "nobody" if ns.owner is None else ns.owner
aname = "system" if ns.app is None else ns.app
path = UrlEncoded("/servicesNS/%s/%s/%s" % (oname, aname, path_segment),
skip_encode=skip_encode)
return path
示例11: login
# 需要导入模块: from splunklib import binding [as 别名]
# 或者: from splunklib.binding import Context [as 别名]
def login(self):
"""Logs into the Splunk instance referred to by the :class:`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 :meth:`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...
"""
if self.has_cookies() and \
(not self.username and not self.password):
# If we were passed session cookie(s), but no username or
# password, then login is a nop, since we're automatically
# logged in.
return
if self.token is not _NoAuthenticationToken and \
(not self.username and not self.password):
# If we were passed a session token, but no username or
# password, then login is a nop, since we're automatically
# logged in.
return
if self.basic and (self.username and self.password):
# Basic auth mode requested, so this method is a nop as long
# as credentials were passed in.
return
# Only try to get a token and updated cookie if username & password are specified
try:
response = self.http.post(
self.authority + self._abspath("/services/auth/login"),
username=self.username,
password=self.password,
headers=self.additional_headers,
cookie="1") # In Splunk 6.2+, passing "cookie=1" will return the "set-cookie" header
body = response.body.read()
session = XML(body).findtext("./sessionKey")
self.token = "Splunk %s" % session
return self
except HTTPError as he:
if he.status == 401:
raise AuthenticationError("Login failed.", he)
else:
raise