INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get answers either from inner_hits already present or by searching elasticsearch. | def get_answers(self):
"""
Get answers either from inner_hits already present or by searching
elasticsearch.
"""
if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits:
return self.meta.inner_hits.answer.hits
return list(self.search_answers()) |
Return the aggregation object. | def get_aggregation(self):
"""
Return the aggregation object.
"""
agg = A(self.agg_type, **self._params)
if self._metric:
agg.metric('metric', self._metric)
return agg |
Construct a filter. | def add_filter(self, filter_values):
"""
Construct a filter.
"""
if not filter_values:
return
f = self.get_value_filter(filter_values[0])
for v in filter_values[1:]:
f |= self.get_value_filter(v)
return f |
Turn the raw bucket data into a list of tuples containing the key number of documents and a flag indicating whether this value has been selected or not. | def get_values(self, data, filter_values):
"""
Turn the raw bucket data into a list of tuples containing the key,
number of documents and a flag indicating whether this value has been
selected or not.
"""
out = []
for bucket in data.buckets:
key = self... |
Add a filter for a facet. | def add_filter(self, name, filter_values):
"""
Add a filter for a facet.
"""
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [filter_values, ]
# re... |
Returns the base Search object to which the facets are added. | def search(self):
"""
Returns the base Search object to which the facets are added.
You can customize the query by overriding this method and returning a
modified search object.
"""
s = Search(doc_type=self.doc_types, index=self.index, using=self.using)
return s.... |
Add query part to search. | def query(self, search, query):
"""
Add query part to ``search``.
Override this if you wish to customize the query used.
"""
if query:
if self.fields:
return search.query('multi_match', fields=self.fields, query=query)
else:
... |
Add aggregations representing the facets selected including potential filters. | def aggregate(self, search):
"""
Add aggregations representing the facets selected, including potential
filters.
"""
for f, facet in iteritems(self.facets):
agg = facet.get_aggregation()
agg_filter = MatchAll()
for field, filter in iteritems(se... |
Add a post_filter to the search request narrowing the results based on the facet filters. | def filter(self, search):
"""
Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.
"""
if not self._filters:
return search
post_filter = MatchAll()
for f in itervalues(self._filters):
post_filter &=... |
Add highlighting for all the fields | def highlight(self, search):
"""
Add highlighting for all the fields
"""
return search.highlight(*(f if '^' not in f else f.split('^', 1)[0]
for f in self.fields)) |
Add sorting information to the request. | def sort(self, search):
"""
Add sorting information to the request.
"""
if self._sort:
search = search.sort(*self._sort)
return search |
Construct the Search object. | def build_search(self):
"""
Construct the ``Search`` object.
"""
s = self.search()
s = self.query(s, self._query)
s = self.filter(s)
if self.fields:
s = self.highlight(s)
s = self.sort(s)
self.aggregate(s)
return s |
Execute the search and return the response. | def execute(self):
"""
Execute the search and return the response.
"""
r = self._s.execute()
r._faceted_search = self
return r |
Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https:// elasticsearch - py. readthedocs. io/ en/ master/ api. html#elasticsearch. Elasticsearch. search for all available parameters. | def params(self, **kwargs):
"""
Specify query params to be used when executing the search. All the
keyword arguments will override the current values. See
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search
for all available parameters.
... |
Set the index for the search. If called empty it will remove all information. | def index(self, *index):
"""
Set the index for the search. If called empty it will remove all information.
Example:
s = Search()
s = s.index('twitter-2015.01.01', 'twitter-2015.01.02')
s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02'])
"""
... |
Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of Document. | def doc_type(self, *doc_type, **kwargs):
"""
Set the type to search through. You can supply a single value or
multiple. Values can be strings or subclasses of ``Document``.
You can also pass in any keyword arguments, mapping a doc_type to a
callback that should be used instead o... |
Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. | def using(self, client):
"""
Associate the search request with an elasticsearch client. A fresh copy
will be returned with current instance remaining unchanged.
:arg client: an instance of ``elasticsearch.Elasticsearch`` to use or
an alias to look up in ``elasticsearch_dsl.c... |
Add extra keys to the request body. Mostly here for backwards compatibility. | def extra(self, **kwargs):
"""
Add extra keys to the request body. Mostly here for backwards
compatibility.
"""
s = self._clone()
if 'from_' in kwargs:
kwargs['from'] = kwargs.pop('from_')
s._extra.update(kwargs)
return s |
Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used internally by most state modifying APIs. | def _clone(self):
"""
Return a clone of the current search request. Performs a shallow copy
of all the underlying objects. Used internally by most state modifying
APIs.
"""
s = super(Search, self)._clone()
s._response_class = self._response_class
s._sort ... |
Override the default wrapper used for the response. | def response_class(self, cls):
"""
Override the default wrapper used for the response.
"""
s = self._clone()
s._response_class = cls
return s |
Apply options from a serialized body to the current instance. Modifies the object in - place. Used mostly by from_dict. | def update_from_dict(self, d):
"""
Apply options from a serialized body to the current instance. Modifies
the object in-place. Used mostly by ``from_dict``.
"""
d = d.copy()
if 'query' in d:
self.query._proxied = Q(d.pop('query'))
if 'post_filter' in d... |
Define script fields to be calculated on hits. See https:// www. elastic. co/ guide/ en/ elasticsearch/ reference/ current/ search - request - script - fields. html for more details. | def script_fields(self, **kwargs):
"""
Define script fields to be calculated on hits. See
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
for more details.
Example::
s = Search()
s = s.script_fields(times... |
Selectively control how the _source field is returned. | def source(self, fields=None, **kwargs):
"""
Selectively control how the _source field is returned.
:arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes
If ``fields`` is None, the entire document will be returned for
each hit. If fields is a... |
Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: | def sort(self, *keys):
"""
Add sorting information to the search request. If called without
arguments it will remove all sort requirements. Otherwise it will
replace them. Acceptable arguments are::
'some.field'
'-some.other.field'
{'different.field':... |
Update the global highlighting options used for this request. For example:: | def highlight_options(self, **kwargs):
"""
Update the global highlighting options used for this request. For
example::
s = Search()
s = s.highlight_options(order='score')
"""
s = self._clone()
s._highlight_opts.update(kwargs)
return s |
Request highlighting of some fields. All keyword arguments passed in will be used as parameters for all the fields in the fields parameter. Example:: | def highlight(self, *fields, **kwargs):
"""
Request highlighting of some fields. All keyword arguments passed in will be
used as parameters for all the fields in the ``fields`` parameter. Example::
Search().highlight('title', 'body', fragment_size=50)
will produce the equiv... |
Add a suggestions request to the search. | def suggest(self, name, text, **kwargs):
"""
Add a suggestions request to the search.
:arg name: name of the suggestion
:arg text: text to suggest on
All keyword arguments will be added to the suggestions body. For example::
s = Search()
s = s.suggest('... |
Serialize the search into the dictionary that will be sent over as the request s body. | def to_dict(self, count=False, **kwargs):
"""
Serialize the search into the dictionary that will be sent over as the
request's body.
:arg count: a flag to specify if we are interested in a body for count -
no aggregations, no pagination bounds etc.
All additional ke... |
Return the number of hits matching the query and filters. Note that only the actual number is returned. | def count(self):
"""
Return the number of hits matching the query and filters. Note that
only the actual number is returned.
"""
if hasattr(self, '_response'):
return self._response.hits.total
es = connections.get_connection(self._using)
d = self.to_... |
Execute the search and return an instance of Response wrapping all the data. | def execute(self, ignore_cache=False):
"""
Execute the search and return an instance of ``Response`` wrapping all
the data.
:arg ignore_cache: if set to ``True``, consecutive calls will hit
ES, while cached result will be ignored. Defaults to `False`
"""
if i... |
Turn the search into a scan search and return a generator that will iterate over all the documents matching the query. | def scan(self):
"""
Turn the search into a scan search and return a generator that will
iterate over all the documents matching the query.
Use ``params`` method to specify any additional arguments you with to
pass to the underlying ``scan`` helper from ``elasticsearch-py`` -
... |
delete () executes the query by delegating to delete_by_query () | def delete(self):
"""
delete() executes the query by delegating to delete_by_query()
"""
es = connections.get_connection(self._using)
return AttrDict(
es.delete_by_query(
index=self._index,
body=self.to_dict(),
**self.... |
Adds a new: class: ~elasticsearch_dsl. Search object to the request:: | def add(self, search):
"""
Adds a new :class:`~elasticsearch_dsl.Search` object to the request::
ms = MultiSearch(index='my-index')
ms = ms.add(Search(doc_type=Category).filter('term', category='python'))
ms = ms.add(Search(doc_type=Blog))
"""
ms = se... |
Execute the multi search request and return a list of search results. | def execute(self, ignore_cache=False, raise_on_error=True):
"""
Execute the multi search request and return a list of search results.
"""
if ignore_cache or not hasattr(self, '_response'):
es = connections.get_connection(self._using)
responses = es.msearch(
... |
Create a tar file from all the files under base_dir. This file may be compressed. | def make_tarball(
base_name,
base_dir,
compress="gzip",
verbose=0,
dry_run=0,
owner=None,
group=None,
):
"""Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the... |
Start the GSS - API/ SSPI Authenticated Diffie - Hellman Key Exchange. | def start_kex(self):
"""
Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange.
"""
self._generate_x()
if self.transport.server_mode:
# compute f = g^x mod p, but don't send it yet
self.f = pow(self.G, self.x, self.P)
self.transpor... |
Parse the next packet. | def parse_next(self, ptype, m):
"""
Parse the next packet.
:param ptype: The (string) type of the incoming packet
:param `.Message` m: The paket content
"""
if self.transport.server_mode and (ptype == MSG_KEXGSS_INIT):
return self._parse_kexgss_init(m)
... |
Parse the SSH2_MSG_KEXGSS_HOSTKEY message ( client mode ). | def _parse_kexgss_hostkey(self, m):
"""
Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode).
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message
"""
# client mode
host_key = m.get_string()
self.transport.host_key = host_key
sig = m... |
Parse the SSH2_MSG_KEXGSS_CONTINUE message. | def _parse_kexgss_continue(self, m):
"""
Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message
"""
if not self.transport.server_mode:
srv_token = m.get_string()
m = Message()
... |
Parse the SSH2_MSG_KEXGSS_COMPLETE message ( client mode ). | def _parse_kexgss_complete(self, m):
"""
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode).
:param `.Message` m: The content of the
SSH2_MSG_KEXGSS_COMPLETE message
"""
# client mode
if self.transport.host_key is None:
self.transport.host_k... |
Parse the SSH2_MSG_KEXGSS_INIT message ( server mode ). | def _parse_kexgss_init(self, m):
"""
Parse the SSH2_MSG_KEXGSS_INIT message (server mode).
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message
"""
# server mode
client_token = m.get_string()
self.e = m.get_mpint()
if (self.e < 1) or (self... |
Start the GSS - API/ SSPI Authenticated Diffie - Hellman Group Exchange | def start_kex(self):
"""
Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange
"""
if self.transport.server_mode:
self.transport._expect_packet(MSG_KEXGSS_GROUPREQ)
return
# request a bit range: we accept (min_bits) to (max_bits), but prefer... |
Parse the next packet. | def parse_next(self, ptype, m):
"""
Parse the next packet.
:param ptype: The (string) type of the incoming packet
:param `.Message` m: The paket content
"""
if ptype == MSG_KEXGSS_GROUPREQ:
return self._parse_kexgss_groupreq(m)
elif ptype == MSG_KEXGS... |
Parse the SSH2_MSG_KEXGSS_GROUP message ( client mode ). | def _parse_kexgss_group(self, m):
"""
Parse the SSH2_MSG_KEXGSS_GROUP message (client mode).
:param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message
"""
self.p = m.get_mpint()
self.g = m.get_mpint()
# reject if p's bit length < 1024 or > 8192
... |
Parse the SSH2_MSG_KEXGSS_COMPLETE message ( client mode ). | def _parse_kexgss_complete(self, m):
"""
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode).
:param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message
"""
if self.transport.host_key is None:
self.transport.host_key = NullHostKey()
self.f =... |
Parse the SSH2_MSG_KEXGSS_ERROR message ( client mode ). The server may send a GSS - API error message. if it does we display the error by throwing an exception ( client mode ). | def _parse_kexgss_error(self, m):
"""
Parse the SSH2_MSG_KEXGSS_ERROR message (client mode).
The server may send a GSS-API error message. if it does, we display
the error by throwing an exception (client mode).
:param `Message` m: The content of the SSH2_MSG_KEXGSS_ERROR messag... |
Create an. SFTPAttributes object from an existing stat object ( an object returned by os. stat ). | def from_stat(cls, obj, filename=None):
"""
Create an `.SFTPAttributes` object from an existing ``stat`` object (an
object returned by `os.stat`).
:param object obj: an object returned by `os.stat` (or equivalent).
:param str filename: the filename associated with this file.
... |
Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. | def generate(bits, progress_func=None):
"""
Generate a new private RSA key. This factory function can be used to
generate a new host key or authentication key.
:param int bits: number of bits the generated key should be.
:param progress_func: Unused
:return: new `.RSAKe... |
if a block of data is present in the prefetch buffers at the given offset return the offset of the relevant prefetch buffer. otherwise return None. this guarantees nothing about the number of bytes collected in the prefetch buffer so far. | def _data_in_prefetch_buffers(self, offset):
"""
if a block of data is present in the prefetch buffers, at the given
offset, return the offset of the relevant prefetch buffer. otherwise,
return None. this guarantees nothing about the number of bytes
collected in the prefetch bu... |
Set the file s current position. | def seek(self, offset, whence=0):
"""
Set the file's current position.
See `file.seek` for details.
"""
self.flush()
if whence == self.SEEK_SET:
self._realpos = self._pos = offset
elif whence == self.SEEK_CUR:
self._pos += offset
... |
Retrieve information about this file from the remote system. This is exactly like. SFTPClient. stat except that it operates on an already - open file. | def stat(self):
"""
Retrieve information about this file from the remote system. This is
exactly like `.SFTPClient.stat`, except that it operates on an
already-open file.
:returns:
an `.SFTPAttributes` object containing attributes about this file.
"""
... |
Change the size of this file. This usually extends or shrinks the size of the file just like the truncate () method on Python file objects. | def truncate(self, size):
"""
Change the size of this file. This usually extends
or shrinks the size of the file, just like the ``truncate()`` method on
Python file objects.
:param size: the new size of the file
"""
self.sftp._log(
DEBUG, "truncate({... |
Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download or for various rsync - like operations. | def check(self, hash_algorithm, offset=0, length=0, block_size=0):
"""
Ask the server for a hash of a section of this file. This can be used
to verify a successful upload or download, or for various rsync-like
operations.
The file is hashed from ``offset``, for ``length`` bytes... |
Pre - fetch the remaining contents of this file in anticipation of future. read calls. If reading the entire file pre - fetching can dramatically improve the download speed by avoiding roundtrip latency. The file s contents are incrementally buffered in a background thread. | def prefetch(self, file_size=None):
"""
Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls. If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementall... |
Read a set of blocks from the file by ( offset length ). This is more efficient than doing a series of. seek and. read calls since the prefetch machinery is used to retrieve all the requested blocks at once. | def readv(self, chunks):
"""
Read a set of blocks from the file by (offset, length). This is more
efficient than doing a series of `.seek` and `.read` calls, since the
prefetch machinery is used to retrieve all the requested blocks at
once.
:param chunks:
a ... |
if there s a saved exception raise & clear it | def _check_exception(self):
"""if there's a saved exception, raise & clear it"""
if self._saved_exception is not None:
x = self._saved_exception
self._saved_exception = None
raise x |
Decorator for. Channel methods which performs an openness check. | def open_only(func):
"""
Decorator for `.Channel` methods which performs an openness check.
:raises:
`.SSHException` -- If the wrapped method is called on an unopened
`.Channel`.
"""
@wraps(func)
def _check(self, *args, **kwds):
if (
self.closed
... |
Execute a command on the server. If the server allows it the channel will then be directly connected to the stdin stdout and stderr of the command being executed. | def exec_command(self, command):
"""
Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be closed and
... |
Resize the pseudo - terminal. This can be used to change the width and height of the terminal emulation created in a previous get_pty call. | def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0):
"""
Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous `get_pty` call.
:param int width: new width (in characters) of the terminal screen... |
Updates this channel s remote shell environment. | def update_environment(self, environment):
"""
Updates this channel's remote shell environment.
.. note::
This operation is additive - i.e. the current environment is not
reset before the given environment variables are set.
.. warning::
Servers may ... |
Set the value of an environment variable. | def set_environment_variable(self, name, value):
"""
Set the value of an environment variable.
.. warning::
The server may reject this request depending on its ``AcceptEnv``
setting; such rejections will fail silently (which is common client
practice for this... |
Return the exit status from the process on the server. This is mostly useful for retrieving the results of an exec_command. If the command hasn t finished yet this method will wait until it does or until the channel is closed. If no exit status is provided by the server - 1 is returned. | def recv_exit_status(self):
"""
Return the exit status from the process on the server. This is
mostly useful for retrieving the results of an `exec_command`.
If the command hasn't finished yet, this method will wait until
it does, or until the channel is closed. If no exit stat... |
Request an x11 session on this channel. If the server allows it further x11 requests can be made from the server to the client when an x11 application is run in a shell session. | def request_x11(
self,
screen_number=0,
auth_protocol=None,
auth_cookie=None,
single_connection=False,
handler=None,
):
"""
Request an x11 session on this channel. If the server allows it,
further x11 requests can be made from the server to th... |
Request for a forward SSH Agent on this channel. This is only valid for an ssh - agent from OpenSSH !!! | def request_forward_agent(self, handler):
"""
Request for a forward SSH Agent on this channel.
This is only valid for an ssh-agent from OpenSSH !!!
:param handler:
a required callable handler to use for incoming SSH Agent
connections
:return: True if we ... |
Set whether stderr should be combined into stdout on this channel. The default is False but in some cases it may be convenient to have both streams combined. | def set_combine_stderr(self, combine):
"""
Set whether stderr should be combined into stdout on this channel.
The default is ``False``, but in some cases it may be convenient to
have both streams combined.
If this is ``False``, and `exec_command` is called (or ``invoke_shell``
... |
Close the channel. All future read/ write operations on the channel will fail. The remote end will receive no more data ( after queued data is flushed ). Channels are automatically closed when their. Transport is closed or when they are garbage collected. | def close(self):
"""
Close the channel. All future read/write operations on the channel
will fail. The remote end will receive no more data (after queued data
is flushed). Channels are automatically closed when their `.Transport`
is closed or when they are garbage collected.
... |
Returns true if data can be written to this channel without blocking. This means the channel is either closed ( so any write attempt would return immediately ) or there is at least one byte of space in the outbound buffer. If there is at least one byte of space in the outbound buffer a send call will succeed immediatel... | def send_ready(self):
"""
Returns true if data can be written to this channel without blocking.
This means the channel is either closed (so any write attempt would
return immediately) or there is at least one byte of space in the
outbound buffer. If there is at least one byte of ... |
Send data to the channel. Returns the number of bytes sent or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted the application needs to attempt delivery of the remaining data. | def send(self, s):
"""
Send data to the channel. Returns the number of bytes sent, or 0 if
the channel stream is closed. Applications are responsible for
checking that all data has been sent: if only some of the data was
transmitted, the application needs to attempt delivery of... |
Send data to the channel on the stderr stream. This is normally only used by servers to send output from shell commands -- clients won t use this. Returns the number of bytes sent or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was tr... | def send_stderr(self, s):
"""
Send data to the channel on the "stderr" stream. This is normally
only used by servers to send output from shell commands -- clients
won't use this. Returns the number of bytes sent, or 0 if the channel
stream is closed. Applications are responsib... |
Send data to the channel without allowing partial results. Unlike send this method continues to send data from the given string until either all data has been sent or an error occurs. Nothing is returned. | def sendall(self, s):
"""
Send data to the channel, without allowing partial results. Unlike
`send`, this method continues to send data from the given string until
either all data has been sent or an error occurs. Nothing is returned.
:param str s: data to send.
:rais... |
Send data to the channel s stderr stream without allowing partial results. Unlike send_stderr this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. | def sendall_stderr(self, s):
"""
Send data to the channel's "stderr" stream, without allowing partial
results. Unlike `send_stderr`, this method continues to send data
from the given string until all data has been sent or an error occurs.
Nothing is returned.
:param str... |
Returns an OS - level file descriptor which can be used for polling but but not for reading or writing. This is primarily to allow Python s select module to work. | def fileno(self):
"""
Returns an OS-level file descriptor which can be used for polling, but
but not for reading or writing. This is primarily to allow Python's
``select`` module to work.
The first time ``fileno`` is called on a channel, a pipe is created to
simulate re... |
Shut down one or both halves of the connection. If how is 0 further receives are disallowed. If how is 1 further sends are disallowed. If how is 2 further sends and receives are disallowed. This closes the stream in one or both directions. | def shutdown(self, how):
"""
Shut down one or both halves of the connection. If ``how`` is 0,
further receives are disallowed. If ``how`` is 1, further sends
are disallowed. If ``how`` is 2, further sends and receives are
disallowed. This closes the stream in one or both dire... |
( You are already holding the lock. ) Wait for the send window to open up and allocate up to size bytes for transmission. If no space opens up before the timeout a timeout exception is raised. Returns the number of bytes available to send ( may be less than requested ). | def _wait_for_send_window(self, size):
"""
(You are already holding the lock.)
Wait for the send window to open up, and allocate up to ``size`` bytes
for transmission. If no space opens up before the timeout, a timeout
exception is raised. Returns the number of bytes available ... |
Convert an errno value ( as from an OSError or IOError ) into a standard SFTP result code. This is a convenience function for trapping exceptions in server code and returning an appropriate result. | def convert_errno(e):
"""
Convert an errno value (as from an ``OSError`` or ``IOError``) into a
standard SFTP result code. This is a convenience function for trapping
exceptions in server code and returning an appropriate result.
:param int e: an errno code, as from ``OSError.e... |
convert SFTP - style open () flags to Python s os. open () flags | def _convert_pflags(self, pflags):
"""convert SFTP-style open() flags to Python's os.open() flags"""
if (pflags & SFTP_FLAG_READ) and (pflags & SFTP_FLAG_WRITE):
flags = os.O_RDWR
elif pflags & SFTP_FLAG_WRITE:
flags = os.O_WRONLY
else:
flags = os.O_RD... |
Set an event on this buffer. When data is ready to be read ( or the buffer has been closed ) the event will be set. When no data is ready the event will be cleared. | def set_event(self, event):
"""
Set an event on this buffer. When data is ready to be read (or the
buffer has been closed), the event will be set. When no data is
ready, the event will be cleared.
:param threading.Event event: the event to set/clear
"""
self._l... |
Feed new data into this pipe. This method is assumed to be called from a separate thread so synchronization is done. | def feed(self, data):
"""
Feed new data into this pipe. This method is assumed to be called
from a separate thread, so synchronization is done.
:param data: the data to add, as a ``str`` or ``bytes``
"""
self._lock.acquire()
try:
if self._event is no... |
Returns true if data is buffered and ready to be read from this feeder. A False result does not mean that the feeder has closed ; it means you may need to wait before more data arrives. | def read_ready(self):
"""
Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `read` call would immediatel... |
Read data from the pipe. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by nbytes. If a string of length zero is returned the pipe has been closed. | def read(self, nbytes, timeout=None):
"""
Read data from the pipe. The return value is a string representing
the data received. The maximum amount of data to be received at once
is specified by ``nbytes``. If a string of length zero is returned,
the pipe has been closed.
... |
Clear out the buffer and return all data that was in it. | def empty(self):
"""
Clear out the buffer and return all data that was in it.
:return:
any data that was in the buffer prior to clearing it out, as a
`str`
"""
self._lock.acquire()
try:
out = self._buffer_tobytes()
del self... |
Close this pipe object. Future calls to read after the buffer has been emptied will return immediately with an empty string. | def close(self):
"""
Close this pipe object. Future calls to `read` after the buffer
has been emptied will return immediately with an empty string.
"""
self._lock.acquire()
try:
self._closed = True
self._cv.notifyAll()
if self._event i... |
Read an OpenSSH config from the given file object. | def parse(self, file_obj):
"""
Read an OpenSSH config from the given file object.
:param file_obj: a file-like object to read the config file from
"""
host = {"host": ["*"], "config": {}}
for line in file_obj:
# Strip any leading or trailing whitespace from t... |
Return a dict ( SSHConfigDict ) of config options for a given hostname. | def lookup(self, hostname):
"""
Return a dict (`SSHConfigDict`) of config options for a given hostname.
The host-matching rules of OpenSSH's ``ssh_config`` man page are used:
For each parameter, the first obtained value will be used. The
configuration files contain sections sep... |
Return the set of literal hostnames defined in the SSH config ( both explicit hostnames and wildcard entries ). | def get_hostnames(self):
"""
Return the set of literal hostnames defined in the SSH config (both
explicit hostnames and wildcard entries).
"""
hosts = set()
for entry in self._config:
hosts.update(entry["host"])
return hosts |
Return a dict of config options with expanded substitutions for a given hostname. | def _expand_variables(self, config, hostname):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ``ssh_config`` for the parameters that
are replaced.
:param dict config: the config for the hostname
:param s... |
Return a list of host_names from host value. | def _get_hosts(self, host):
"""
Return a list of host_names from host value.
"""
try:
return shlex.split(host)
except ValueError:
raise Exception("Unparsable host {}".format(host)) |
Express given key s value as a boolean type. | def as_bool(self, key):
"""
Express given key's value as a boolean type.
Typically, this is used for ``ssh_config``'s pseudo-boolean values
which are either ``"yes"`` or ``"no"``. In such cases, ``"yes"`` yields
``True`` and any other value becomes ``False``.
.. note::
... |
Authenticate the given user to the server if he is a valid krb5 principal. | def check_auth_gssapi_with_mic(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal.
:param str username: The username of the authenticating client
:param int gss_authenticated: ... |
Authenticate the given user to the server if he is a valid krb5 principal and GSS - API Key Exchange was performed. If GSS - API Key Exchange was not performed this authentication method won t be available. | def check_auth_gssapi_keyex(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal and GSS-API Key Exchange was performed.
If GSS-API Key Exchange was not performed, this authentication met... |
Determine if a requested subsystem will be provided to the client on the given channel. If this method returns True all future I/ O through this channel will be assumed to be connected to the requested subsystem. An example of a subsystem is sftp. | def check_channel_subsystem_request(self, channel, name):
"""
Determine if a requested subsystem will be provided to the client on
the given channel. If this method returns ``True``, all future I/O
through this channel will be assumed to be connected to the requested
subsystem. ... |
Add a prompt to this query. The prompt should be a ( reasonably short ) string. Multiple prompts can be added to the same query. | def add_prompt(self, prompt, echo=True):
"""
Add a prompt to this query. The prompt should be a (reasonably short)
string. Multiple prompts can be added to the same query.
:param str prompt: the user prompt
:param bool echo:
``True`` (default) if the user's respons... |
Provide SSH2 GSS - API/ SSPI authentication. | def GSSAuth(auth_method, gss_deleg_creds=True):
"""
Provide SSH2 GSS-API / SSPI authentication.
:param str auth_method: The name of the SSH authentication mechanism
(gssapi-with-mic or gss-keyex)
:param bool gss_deleg_creds: Delegate client credentials or not.
... |
This method returns a single OID because we only support the Kerberos V5 mechanism. | def ssh_gss_oids(self, mode="client"):
"""
This method returns a single OID, because we only support the
Kerberos V5 mechanism.
:param str mode: Client for client mode and server for server mode
:return: A byte sequence containing the number of supported
OIDs, t... |
Check if the given OID is the Kerberos V5 OID ( server mode ). | def ssh_check_mech(self, desired_mech):
"""
Check if the given OID is the Kerberos V5 OID (server mode).
:param str desired_mech: The desired GSS-API mechanism of the client
:return: ``True`` if the given OID is supported, otherwise C{False}
"""
from pyasn1.codec.der imp... |
Create the SSH2 MIC filed for gssapi - with - mic. | def _ssh_build_mic(self, session_id, username, service, auth_method):
"""
Create the SSH2 MIC filed for gssapi-with-mic.
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:param str service: The requested SSH service
... |
Initialize a GSS - API context. | def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a GSS-API context.
:param str username: The name of the user who attempts to login
:param str target: The hostname of the target to connect to
:param str desir... |
Accept a GSS - API context ( server mode ). | def ssh_accept_sec_context(self, hostname, recv_token, username=None):
"""
Accept a GSS-API context (server mode).
:param str hostname: The servers hostname
:param str username: The name of the user who attempts to login
:param str recv_token: The GSS-API Token received from the... |
Initialize a SSPI context. | def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a SSPI context.
:param str username: The name of the user who attempts to login
:param str target: The FQDN of the target to connect to
:param str desired_mech... |
Create the MIC token for a SSH2 message. | def ssh_get_mic(self, session_id, gss_kex=False):
"""
Create the MIC token for a SSH2 message.
:param str session_id: The SSH session ID
:param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not
:return: gssapi-with-mic:
Returns the MIC token from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.