INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Gets all data from the todo files in indexq and returns one huge list of all data. | def get_all_json_from_indexq(self):
'''
Gets all data from the todo files in indexq and returns one huge list of all data.
'''
files = self.get_all_as_list()
out = []
for efile in files:
out.extend(self._open_file(efile))
return out |
This helps indexq operate in multiprocessing environment without each process having to have it s own IndexQ. It also is a handy way to deal with thread/ process safety. | def get_multi_q(self, sentinel='STOP'):
'''
This helps indexq operate in multiprocessing environment without each process having to have it's own IndexQ. It also is a handy way to deal with thread / process safety.
This method will create and return a JoinableQueue object. Additionally, it will... |
Internal mechanism to try to send data to multiple Solr Hosts if the query fails on the first one. | def _retry(function):
"""
Internal mechanism to try to send data to multiple Solr Hosts if
the query fails on the first one.
"""
def inner(self, **kwargs):
last_exception = None
#for host in self.router.get_hosts(**kwargs):
for host in self.ho... |
: param str collection: The name of the collection for the request: param bool openSearcher: If new searcher is to be opened: param bool softCommit: SoftCommit: param bool waitServer: Blocks until the new searcher is opened: param bool commit: Commit | def commit(self, collection, openSearcher=False, softCommit=False,
waitSearcher=True, commit=True, **kwargs):
"""
:param str collection: The name of the collection for the request
:param bool openSearcher: If new searcher is to be opened
:param bool softCommit: SoftCommit
... |
: param str collection: The name of the collection for the request: param str request_handler: Request handler default is select: param dict query: Python dictionary of Solr query parameters. | def query_raw(self, collection, query, request_handler='select', **kwargs):
"""
:param str collection: The name of the collection for the request
:param str request_handler: Request handler, default is 'select'
:param dict query: Python dictionary of Solr query parameters.
Sends... |
: param str collection: The name of the collection for the request: param str request_handler: Request handler default is select: param dict query: Python dictonary of Solr query parameters. | def query(self, collection, query, request_handler='select', **kwargs):
"""
:param str collection: The name of the collection for the request
:param str request_handler: Request handler, default is 'select'
:param dict query: Python dictonary of Solr query parameters.
Sends a qu... |
: param str collection: The name of the collection for the request.: param docs list docs: List of dicts. ex: [ { title: testing solr indexing id: test1 } ]: param min_rf int min_rf: Required number of replicas to write to | def index(self, collection, docs, params=None, min_rf=None, **kwargs):
"""
:param str collection: The name of the collection for the request.
:param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}]
:param min_rf int min_rf: Required number of replica... |
: param str collection: The name of the collection for the request.: param data str data: Valid Solr JSON as a string. ex: [ { title: testing solr indexing id: test1 } ]: param min_rf int min_rf: Required number of replicas to write to | def index_json(self, collection, data, params=None, min_rf=None, **kwargs):
"""
:param str collection: The name of the collection for the request.
:param data str data: Valid Solr JSON as a string. ex: '[{"title": "testing solr indexing", "id": "test1"}]'
:param min_rf int min_rf: Requir... |
: param str collection: The name of the collection for the request: param str doc_id: ID of the document to be retrieved. | def get(self, collection, doc_id, **kwargs):
"""
:param str collection: The name of the collection for the request
:param str doc_id: ID of the document to be retrieved.
Retrieve document from Solr based on the ID. ::
>>> solr.get('SolrClient_unittest','changeme')
"... |
: param str collection: The name of the collection for the request: param tuple doc_ids: ID of the document to be retrieved. | def mget(self, collection, doc_ids, **kwargs):
"""
:param str collection: The name of the collection for the request
:param tuple doc_ids: ID of the document to be retrieved.
Retrieve documents from Solr based on the ID. ::
>>> solr.get('SolrClient_unittest','changeme')
... |
: param str collection: The name of the collection for the request: param str id: ID of the document to be deleted. Can specify * to delete everything. | def delete_doc_by_id(self, collection, doc_id, **kwargs):
"""
:param str collection: The name of the collection for the request
:param str id: ID of the document to be deleted. Can specify '*' to delete everything.
Deletes items from Solr based on the ID. ::
>>> solr.delete... |
: param str collection: The name of the collection for the request: param str query: Query selecting documents to be deleted. | def delete_doc_by_query(self, collection, query, **kwargs):
"""
:param str collection: The name of the collection for the request
:param str query: Query selecting documents to be deleted.
Deletes items from Solr based on a given query. ::
>>> solr.delete_doc_by_query('Solr... |
: param str collection: The name of the collection for the request: param str filename: String file path of the file to index. | def local_index(self, collection, filename, **kwargs):
"""
:param str collection: The name of the collection for the request
:param str filename: String file path of the file to index.
Will index specified file into Solr. The `file` must be local to the server, this is faster than other... |
: param str collection: The name of the collection for the request.: param dict query: Dictionary of solr args.: param int rows: Number of rows to return in each batch. Default is 1000.: param int start: What position to start with. Default is 0.: param int max_start: Once the start will reach this number the function ... | def paging_query(self, collection, query, rows=1000, start=0, max_start=200000):
"""
:param str collection: The name of the collection for the request.
:param dict query: Dictionary of solr args.
:param int rows: Number of rows to return in each batch. Default is 1000.
:param int... |
: param str collection: The name of the collection for the request.: param dict query: Dictionary of solr args. | def cursor_query(self, collection, query):
"""
:param str collection: The name of the collection for the request.
:param dict query: Dictionary of solr args.
Will page through the result set in increments using cursorMark until it has all items. Sort is required for cursorMark \
... |
You can change this function to get the shard - map from somewhere/ somehow place else in conjuction with save_shard_map (). | def get_shard_map(self, force_refresh=False):
"""
You can change this function to get the shard-map from somewhere/somehow place else in conjuction with
save_shard_map().
"""
now = datetime.utcnow()
if force_refresh is True or \
self.shard_map is ... |
Will attempt to telnet to each zookeeper that is used by SolrClient and issue mntr command. Response is parsed to check to see if the zookeeper node is a leader or a follower and returned as a dict. | def check_zk(self):
'''
Will attempt to telnet to each zookeeper that is used by SolrClient and issue 'mntr' command. Response is parsed to check to see if the
zookeeper node is a leader or a follower and returned as a dict.
If the telnet collection fails or the proper response is not... |
Copies collection configs into a new folder. Can be used to create new collections based on existing configs. | def copy_config(self, original, new):
'''
Copies collection configs into a new folder. Can be used to create new collections based on existing configs.
Basically, copies all nodes under /configs/original to /configs/new.
:param original str: ZK name of original config
:param n... |
Downloads ZK Directory to the FileSystem. | def download_collection_configs(self, collection, fs_path):
'''
Downloads ZK Directory to the FileSystem.
:param collection str: Name of the collection (zk config name)
:param fs_path str: Destination filesystem path.
'''
if not self.kz.exists('/configs/{}'.for... |
Uploads collection configurations from a specified directory to zookeeper. | def upload_collection_configs(self, collection, fs_path):
'''
Uploads collection configurations from a specified directory to zookeeper.
'''
coll_path = fs_path
if not os.path.isdir(coll_path):
raise ValueError("{} Doesn't Exist".format(coll_path))
s... |
Creates a new field in managed schema will raise ValueError if the field already exists. field_dict should look like this:: | def create_field(self, collection, field_dict):
'''
Creates a new field in managed schema, will raise ValueError if the field already exists. field_dict should look like this::
{
"name":"sell-by",
"type":"tdate",
"stored":True
... |
Deletes a field from the Solr Collection. Will raise ValueError if the field doesn t exist. | def delete_field(self,collection,field_name):
'''
Deletes a field from the Solr Collection. Will raise ValueError if the field doesn't exist.
:param string collection: Name of the collection for the action
:param string field_name: String name of the field.
'''
if not se... |
Checks if the field exists will return a boolean True ( exists ) or False ( doesn t exist ). | def does_field_exist(self,collection,field_name):
'''
Checks if the field exists will return a boolean True (exists) or False(doesn't exist).
:param string collection: Name of the collection for the action
:param string field_name: String name of the field.
'''
schema = ... |
Creates a copy field. | def create_copy_field(self,collection,copy_dict):
'''
Creates a copy field.
copy_dict should look like ::
{'source':'source_field_name','dest':'destination_field_name'}
:param string collection: Name of the collection for the action
:param dict copy_field: Dictiona... |
Deletes a copy field. | def delete_copy_field(self, collection, copy_dict):
'''
Deletes a copy field.
copy_dict should look like ::
{'source':'source_field_name','dest':'destination_field_name'}
:param string collection: Name of the collection for the action
:param dict copy_field: Dictio... |
Shuffle hosts so we don t always query the first one. Example: using in a webapp with X processes in Y servers the hosts contacted will be more random. The user can also call this function to reshuffle every x seconds or before every request.: return: | def shuffle_hosts(self):
"""
Shuffle hosts so we don't always query the first one.
Example: using in a webapp with X processes in Y servers, the hosts contacted will be more random.
The user can also call this function to reshuffle every 'x' seconds or before every request.
:retu... |
Starts virtual display which will be destroyed after test execution will be end | def start_virtual_display(self, width=1440, height=900,
colordepth=24, **kwargs):
"""Starts virtual display which will be
destroyed after test execution will be end
*Arguments:*
- width: a width to be set in pixels
- height: a height to be set in p... |
Sends a request to Solr Collections API. Documentation is here: https:// cwiki. apache. org/ confluence/ display/ solr/ Collections + API | def api(self, action, args=None):
"""
Sends a request to Solr Collections API.
Documentation is here: https://cwiki.apache.org/confluence/display/solr/Collections+API
:param string action: Name of the collection for the action
:param dict args: Dictionary of specific parameters ... |
Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns it as doc_count key for each replica. | def clusterstatus(self):
"""
Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns
it as doc_count key for each replica.
"""
res = self.cluster_status_raw()
cluster = res['clu... |
Create a new collection. | def create(self, name, numShards, params=None):
"""
Create a new collection.
"""
if params is None:
params = {}
params.update(
name=name,
numShards=numShards
)
return self.api('CREATE', params) |
Queries each core to get individual counts for each core for each shard. | def _get_collection_counts(self, core_data):
"""
Queries each core to get individual counts for each core for each shard.
"""
if core_data['base_url'] not in self.solr_clients:
from SolrClient import SolrClient
self.solr_clients['base_url'] = SolrClient(core_data[... |
Checks status of each collection and shard to make sure that: a ) Cluster state is active b ) Number of docs matches across replicas for a given shard. Returns a dict of results for custom alerting. | def check_status(self, ignore=(), status=None):
"""
Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting.
"""
self.SH... |
Starts Reindexing Process. All parameter arguments will be passed down to the getter function.: param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results. | def reindex(self, fq= [], **kwargs):
'''
Starts Reindexing Process. All parameter arguments will be passed down to the getter function.
:param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results.
'''
for items in self._gette... |
Method for retrieving batch data from Solr. | def _from_solr(self, fq=[], report_frequency = 25):
'''
Method for retrieving batch data from Solr.
'''
cursor = '*'
stime = datetime.now()
query_count = 0
while True:
#Get data with starting cursorMark
query = self._get_query(curs... |
Removes ignore fields from the data that we got from Solr. | def _trim_fields(self, docs):
'''
Removes ignore fields from the data that we got from Solr.
'''
for doc in docs:
for field in self._ignore_fields:
if field in doc:
del(doc[field])
return docs |
Query tempalte for source Solr sorts by id by default. | def _get_query(self, cursor):
'''
Query tempalte for source Solr, sorts by id by default.
'''
query = {'q':'*:*',
'sort':'id desc',
'rows':self._rows,
'cursorMark':cursor}
if self._date_field:
query['sort'] = "{... |
Sends data to a Solr instance. | def _to_solr(self, data):
'''
Sends data to a Solr instance.
'''
return self._dest.index_json(self._dest_coll, json.dumps(data,sort_keys=True)) |
Gets counts of items per specified date range.: param collection: Solr Collection to use.: param timespan: Solr Date Math compliant value for faceting ex HOUR MONTH DAY | def _get_date_range_query(self, start_date, end_date, timespan= 'DAY', date_field= None):
'''
Gets counts of items per specified date range.
:param collection: Solr Collection to use.
:param timespan: Solr Date Math compliant value for faceting ex HOUR, MONTH, DAY
'''
... |
This method is used to get start and end dates for the collection. | def _get_edge_date(self, date_field, sort):
'''
This method is used to get start and end dates for the collection.
'''
return self._source.query(self._source_coll, {
'q':'*:*',
'rows':1,
'fq':'+{}:*'.format(date_field),
... |
Returns Range Facet counts based on | def _get_date_facet_counts(self, timespan, date_field, start_date=None, end_date=None):
'''
Returns Range Facet counts based on
'''
if 'DAY' not in timespan:
raise ValueError("At this time, only DAY date range increment is supported. Aborting..... ")
#Need to ... |
This method may help if the original run was interrupted for some reason. It will only work under the following conditions * You have a date field that you can facet on * Indexing was stopped for the duration of the copy The way this tries to resume re - indexing is by running a date range facet on the source and desti... | def resume(self, start_date=None, end_date=None, timespan='DAY', check= False):
'''
This method may help if the original run was interrupted for some reason. It will only work under the following conditions
* You have a date field that you can facet on
* Indexing was stopped for the ... |
Negotiate a new SSH2 session as a client. This is the first step after creating a new L { Transport }. A separate thread is created for protocol negotiation. | def start_client(self, event=None):
"""
Negotiate a new SSH2 session as a client. This is the first step after
creating a new L{Transport}. A separate thread is created for protocol
negotiation.
If an event is passed in, this method returns immediately. When
negotiati... |
Negotiate a new SSH2 session as a server. This is the first step after creating a new L { Transport } and setting up your server host key ( s ). A separate thread is created for protocol negotiation. | def start_server(self, event=None, server=None):
"""
Negotiate a new SSH2 session as a server. This is the first step after
creating a new L{Transport} and setting up your server host key(s). A
separate thread is created for protocol negotiation.
If an event is passed in, this... |
Close this session and any open channels that are tied to it. | def close(self):
"""
Close this session, and any open channels that are tied to it.
"""
if not self.active:
return
self.active = False
self.packetizer.close()
self.join()
for chan in self._channels.values():
chan._unlink() |
Request a new channel back to the client of type C { forwarded - tcpip }. This is used after a client has requested port forwarding for sending incoming connections back to the client. | def open_forwarded_tcpip_channel(self, (src_addr, src_port), (dest_addr, dest_port)):
"""
Request a new channel back to the client, of type C{"forwarded-tcpip"}.
This is used after a client has requested port forwarding, for sending
incoming connections back to the client.
@para... |
Ask the server to forward TCP connections from a listening port on the server across this SSH session. | def request_port_forward(self, address, port, handler=None):
"""
Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives.... |
Send a junk packet across the encrypted link. This is sometimes used to add noise to a connection to confuse would - be attackers. It can also be used as a keep - alive for long lived connections traversing firewalls. | def send_ignore(self, bytes=None):
"""
Send a junk packet across the encrypted link. This is sometimes used
to add "noise" to a connection to confuse would-be attackers. It can
also be used as a keep-alive for long lived connections traversing
firewalls.
@param bytes: ... |
Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received but this method gives you the option of forcing new keys whenever you want. Negotiating new keys causes a pause in traffic both ways as the two sides swap keys and d... | def renegotiate_keys(self):
"""
Force this session to switch to new keys. Normally this is done
automatically after the session hits a certain number of packets or
bytes sent or received, but this method gives you the option of forcing
new keys whenever you want. Negotiating ne... |
Turn on/ off keepalive packets ( default is off ). If this is set after C { interval } seconds without sending any data over the connection a keepalive packet will be sent ( and ignored by the remote host ). This can be useful to keep connections alive over a NAT for example. | def set_keepalive(self, interval):
"""
Turn on/off keepalive packets (default is off). If this is set, after
C{interval} seconds without sending any data over the connection, a
"keepalive" packet will be sent (and ignored by the remote host). This
can be useful to keep connecti... |
Negotiate an SSH2 session and optionally verify the server s host key and authenticate using a password or private key. This is a shortcut for L { start_client } L { get_remote_server_key } and L { Transport. auth_password } or L { Transport. auth_publickey }. Use those methods if you want more control. | def connect(self, hostkey=None, username='', password=None, pkey=None):
"""
Negotiate an SSH2 session, and optionally verify the server's host key
and authenticate using a password or private key. This is a shortcut
for L{start_client}, L{get_remote_server_key}, and
L{Transport.... |
Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server by catching the L { BadAuthenticationType } exception raised. | def auth_none(self, username):
"""
Try to authenticate to the server using no authentication at all.
This will almost always fail. It may be useful for determining the
list of authentication types supported by the server, by catching the
L{BadAuthenticationType} exception raised... |
send a message but block if we re in key negotiation. this is used for user - initiated requests. | def _send_user_message(self, data):
"""
send a message, but block if we're in key negotiation. this is used
for user-initiated requests.
"""
start = time.time()
while True:
self.clear_to_send.wait(0.1)
if not self.active:
self._log... |
used by a kex object to set the K ( root key ) and H ( exchange hash ) | def _set_K_H(self, k, h):
"used by a kex object to set the K (root key) and H (exchange hash)"
self.K = k
self.H = h
if self.session_id == None:
self.session_id = h |
id is A - F for the various keys used by ssh | def _compute_key(self, id, nbytes):
"id is 'A' - 'F' for the various keys used by ssh"
m = Message()
m.add_mpint(self.K)
m.add_bytes(self.H)
m.add_byte(id)
m.add_bytes(self.session_id)
out = sofar = SHA.new(str(m)).digest()
while len(out) < nbytes:
... |
announce to the other side that we d like to negotiate keys and what kind of key negotiation we support. | def _send_kex_init(self):
"""
announce to the other side that we'd like to negotiate keys, and what
kind of key negotiation we support.
"""
self.clear_to_send_lock.acquire()
try:
self.clear_to_send.clear()
finally:
self.clear_to_send_lock.r... |
primtive attempt at prime generation | def _generate_prime(bits, rng):
"primtive attempt at prime generation"
hbyte_mask = pow(2, bits % 8) - 1
while True:
# loop catches the case where we increment n into a higher bit-range
x = rng.read((bits+7) // 8)
if hbyte_mask > 0:
x = chr(ord(x[0]) & hbyte_mask) + x[1:]... |
returns a random # from 0 to N - 1 | def _roll_random(rng, n):
"returns a random # from 0 to N-1"
bits = util.bit_length(n-1)
bytes = (bits + 7) // 8
hbyte_mask = pow(2, bits % 8) - 1
# so here's the plan:
# we fetch as many random bits as we'd need to fit N-1, and if the
# generated number is >= N, we try again. in the worst... |
Write an SSH2 - format private key file in a form that can be read by ssh or openssh. If no password is given the key is written in a trivially - encoded format ( base64 ) which is completely insecure. If a password is given DES - EDE3 - CBC is used. | def _write_private_key_file(self, tag, filename, data, password=None):
"""
Write an SSH2-format private key file in a form that can be read by
ssh or openssh. If no password is given, the key is written in
a trivially-encoded format (base64) which is completely insecure. If
a p... |
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 event: the event to set/clear
@type event: Event
... |
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
@type data: str
"""
self._lock.acquire()
try:
if self._event ... |
Read up to C { length } bytes from this file starting at position C { offset }. The offset may be a python long since SFTP allows it to be 64 bits. | def read(self, offset, length):
"""
Read up to C{length} bytes from this file, starting at position
C{offset}. The offset may be a python long, since SFTP allows it
to be 64 bits.
If the end of the file has been reached, this method may return an
empty string to signify... |
Write C { data } into this file at position C { offset }. Extending the file past its original end is expected. Unlike python s normal C { write () } methods this method cannot do a partial write: it must write all of C { data } or else return an error. | def write(self, offset, data):
"""
Write C{data} into this file at position C{offset}. Extending the
file past its original end is expected. Unlike python's normal
C{write()} methods, this method cannot do a partial write: it must
write all of C{data} or else return an error.
... |
Return the canonical form of a path on the server. For example if the server s home folder is C {/ home/ foo } the path C {../ betty } would be canonicalized to C {/ home/ betty }. Note the obvious security issues: if you re serving files only from a specific folder you probably don t want this method to reveal path na... | def canonicalize(self, path):
"""
Return the canonical form of a path on the server. For example,
if the server's home folder is C{/home/foo}, the path
C{"../betty"} would be canonicalized to C{"/home/betty"}. Note
the obvious security issues: if you're serving files only from ... |
Method automatically called by the run () method of the AgentProxyThread | def connect(self):
"""
Method automatically called by the run() method of the AgentProxyThread
"""
if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
retry_on_signal(lambd... |
Save the host keys back to a file. Only the host keys loaded with L { load_host_keys } ( plus any added directly ) will be saved -- not any host keys loaded with L { load_system_host_keys }. | def save_host_keys(self, filename):
"""
Save the host keys back to a file. Only the host keys loaded with
L{load_host_keys} (plus any added directly) will be saved -- not any
host keys loaded with L{load_system_host_keys}.
@param filename: the filename to save to
@type ... |
Execute a command on the SSH server. A new L { Channel } is opened and the requested command is executed. The command s input and output streams are returned as python C { file } - like objects representing stdin stdout and stderr. | def exec_command(self, command, bufsize=-1):
"""
Execute a command on the SSH server. A new L{Channel} is opened and
the requested command is executed. The command's input and output
streams are returned as python C{file}-like objects representing
stdin, stdout, and stderr.
... |
Try in order: | def _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys):
"""
Try, in order:
- The key passed in, if one was passed in.
- Any key we can find through an SSH agent (if allowed).
- Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (if all... |
Return the next C { n } bytes of the Message without decomposing into an int string etc. Just the raw bytes are returned. | def get_bytes(self, n):
"""
Return the next C{n} bytes of the Message, without decomposing into
an int, string, etc. Just the raw bytes are returned.
@return: a string of the next C{n} bytes of the Message, or a string
of C{n} zero bytes, if there aren't C{n} bytes remainin... |
Add an integer to the stream. | def add_int(self, n):
"""
Add an integer to the stream.
@param n: integer to add
@type n: int
"""
self.packet.write(struct.pack('>I', n))
return self |
Add a string to the stream. | def add_string(self, s):
"""
Add a string to the stream.
@param s: string to add
@type s: str
"""
self.add_int(len(s))
self.packet.write(s)
return self |
Resize the pseudo - terminal. This can be used to change the width and height of the terminal emulation created in a previous L { get_pty } call. | def resize_pty(self, width=80, height=24):
"""
Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous L{get_pty} call.
@param width: new width (in characters) of the terminal screen
@type width: int
@p... |
Return the exit status from the process on the server. This is mostly useful for retrieving the reults of an L { 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 reults of an L{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... |
Send the exit status of an executed command to the client. ( This really only makes sense in server mode. ) Many clients expect to get some sort of status code back from an executed command after it completes. | def send_exit_status(self, status):
"""
Send the exit status of an executed command to the client. (This
really only makes sense in server mode.) Many clients expect to
get some sort of status code back from an executed command after
it completes.
@param status... |
Receive data from the channel. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by C { nbytes }. If a string of length zero is returned the channel stream has closed. | def recv(self, nbytes):
"""
Receive data from the channel. The return value is a string
representing the data received. The maximum amount of data to be
received at once is specified by C{nbytes}. If a string of length zero
is returned, the channel stream has closed.
... |
Send data to the channel without allowing partial results. Unlike L { 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
L{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 s: data to send.
@type s: ... |
Send data to the channel s stderr stream without allowing partial results. Unlike L { 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 L{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.
@... |
Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. | def agent_auth(transport, username):
"""
Attempt to authenticate to the given transport using any of the private
keys available from an SSH agent.
"""
agent = ssh.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == 0:
return
for key in agent_keys:
pr... |
read data out of the prefetch buffer if possible. if the data isn t in the buffer return None. otherwise behaves like a normal read. | def _read_prefetch(self, size):
"""
read data out of the prefetch buffer, if possible. if the data isn't
in the buffer, return None. otherwise, behaves like a normal read.
"""
# while not closed, and haven't fetched past the current position, and haven't reached EOF...
... |
Change the mode ( permissions ) of this file. The permissions are unix - style and identical to those used by python s C { os. chmod } function. | def chmod(self, mode):
"""
Change the mode (permissions) of this file. The permissions are
unix-style and identical to those used by python's C{os.chmod}
function.
@param mode: new permissions
@type mode: int
"""
self.sftp._log(DEBUG, 'chmod(%s, %r)' % (... |
Change the owner ( C { uid } ) and group ( C { gid } ) of this file. As with python s C { os. chown } function you must pass both arguments so if you only want to change one use L { stat } first to retrieve the current owner and group. | def chown(self, uid, gid):
"""
Change the owner (C{uid}) and group (C{gid}) of this file. As with
python's C{os.chown} function, you must pass both arguments, so if you
only want to change one, use L{stat} first to retrieve the current
owner and group.
@param uid: new o... |
Set the access and modified times of this file. If C { times } is C { None } then the file s access and modified times are set to the current time. Otherwise C { times } must be a 2 - tuple of numbers of the form C { ( atime mtime ) } which is used to set the access and modified times respectively. This bizarre API is ... | def utime(self, times):
"""
Set the access and modified times of this file. If
C{times} is C{None}, then the file's access and modified times are set
to the current time. Otherwise, C{times} must be a 2-tuple of numbers,
of the form C{(atime, mtime)}, which is used to set the a... |
Write out any data in the write buffer. This may do nothing if write buffering is not turned on. | def flush(self):
"""
Write out any data in the write buffer. This may do nothing if write
buffering is not turned on.
"""
self._write_all(self._wbuffer.getvalue())
self._wbuffer = StringIO()
return |
Read one entire line from the file. A trailing newline character is kept in the string ( but may be absent when a file ends with an incomplete line ). If the size argument is present and non - negative it is a maximum byte count ( including the trailing newline ) and an incomplete line may be returned. An empty string ... | def readline(self, size=None):
"""
Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). If the size argument is present and non-negative, it
is a maximum byte count (including the tr... |
Subclasses call this method to initialize the BufferedFile. | def _set_mode(self, mode='r', bufsize=-1):
"""
Subclasses call this method to initialize the BufferedFile.
"""
# set bufsize in any event, because it's used for readline().
self._bufsize = self._DEFAULT_BUFSIZE
if bufsize < 0:
# do no buffering by default, bec... |
Create an SFTP client channel from an open L { Transport }. | def from_transport(cls, t):
"""
Create an SFTP client channel from an open L{Transport}.
@param t: an open L{Transport} which is already authenticated
@type t: L{Transport}
@return: a new L{SFTPClient} object, referring to an sftp session
(channel) across the transpo... |
Return a list containing L { SFTPAttributes } objects corresponding to files in the given C { path }. The list is in arbitrary order. It does not include the special entries C {. } and C {.. } even if they are present in the folder. | def listdir_attr(self, path='.'):
"""
Return a list containing L{SFTPAttributes} objects corresponding to
files in the given C{path}. The list is in arbitrary order. It does
not include the special entries C{'.'} and C{'..'} even if they are
present in the folder.
The ... |
Remove the file at the given path. This only works on files ; for removing folders ( directories ) use L { rmdir }. | def remove(self, path):
"""
Remove the file at the given path. This only works on files; for
removing folders (directories), use L{rmdir}.
@param path: path (absolute or relative) of the file to remove
@type path: str
@raise IOError: if the path refers to a folder (dir... |
Remove the folder named C { path }. | def rmdir(self, path):
"""
Remove the folder named C{path}.
@param path: name of the folder to remove
@type path: str
"""
path = self._adjust_cwd(path)
self._log(DEBUG, 'rmdir(%r)' % path)
self._request(CMD_RMDIR, path) |
Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python s C { stat } structure as returned by C { os. stat } except that it contains fewer fields. An SFTP server may return as much or as little info as it wants so the results may vary... | def stat(self, path):
"""
Retrieve information about a file on the remote system. The return
value is an object whose attributes correspond to the attributes of
python's C{stat} structure as returned by C{os.stat}, except that it
contains fewer fields. An SFTP server may return... |
Retrieve information about a file on the remote system without following symbolic links ( shortcuts ). This otherwise behaves exactly the same as L { stat }. | def lstat(self, path):
"""
Retrieve information about a file on the remote system, without
following symbolic links (shortcuts). This otherwise behaves exactly
the same as L{stat}.
@param path: the filename to stat
@type path: str
@return: an object containing a... |
Create a symbolic link ( shortcut ) of the C { source } path at C { destination }. | def symlink(self, source, dest):
"""
Create a symbolic link (shortcut) of the C{source} path at
C{destination}.
@param source: path of the original file
@type source: str
@param dest: path of the newly created symlink
@type dest: str
"""
dest = se... |
Change the mode ( permissions ) of a file. The permissions are unix - style and identical to those used by python s C { os. chmod } function. | def chmod(self, path, mode):
"""
Change the mode (permissions) of a file. The permissions are
unix-style and identical to those used by python's C{os.chmod}
function.
@param path: path of the file to change the permissions of
@type path: str
@param mode: new per... |
Return the target of a symbolic link ( shortcut ). You can use L { symlink } to create these. The result may be either an absolute or relative pathname. | def readlink(self, path):
"""
Return the target of a symbolic link (shortcut). You can use
L{symlink} to create these. The result may be either an absolute or
relative pathname.
@param path: path of the symbolic link file
@type path: str
@return: target path
... |
Return the normalized path ( on the server ) of a given path. This can be used to quickly resolve symbolic links or determine what the server is considering to be the current folder ( by passing C {. } as C { path } ). | def normalize(self, path):
"""
Return the normalized path (on the server) of a given path. This
can be used to quickly resolve symbolic links or determine what the
server is considering to be the "current folder" (by passing C{'.'}
as C{path}).
@param path: path to be n... |
Copy a remote file ( C { remotepath } ) from the SFTP server to the local host as C { localpath }. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. | def get(self, remotepath, localpath, callback=None):
"""
Copy a remote file (C{remotepath}) from the SFTP server to the local
host as C{localpath}. Any exception raised by operations will be
passed through. This method is primarily provided as a convenience.
@param remotepath:... |
Return an adjusted path if we re emulating a current working directory for the server. | def _adjust_cwd(self, path):
"""
Return an adjusted path if we're emulating a "current working
directory" for the server.
"""
if type(path) is unicode:
path = path.encode('utf-8')
if self._cwd is None:
return path
if (len(path) > 0) and (pa... |
Register a resource to be closed with an object is collected. When the given C { obj } is garbage - collected by the python interpreter the C { resource } will be closed by having its C { close () } method called. Any exceptions are ignored. | def register(self, obj, resource):
"""
Register a resource to be closed with an object is collected.
When the given C{obj} is garbage-collected by the python interpreter,
the C{resource} will be closed by having its C{close()} method called.
Any exceptions are ignored.
... |
Perform HTTP request for REST API. | def _request(self, method, path, data=None, reestablish_session=True):
"""Perform HTTP request for REST API."""
if path.startswith("http"):
url = path # For cases where URL of different form is needed.
else:
url = self._format_path(path)
headers = {"Content-Type... |
Validate a REST API version is supported by the library and target array. | def _check_rest_version(self, version):
"""Validate a REST API version is supported by the library and target array."""
version = str(version)
if version not in self.supported_rest_versions:
msg = "Library is incompatible with REST API version {0}"
raise ValueError(msg.f... |
Return the newest REST API version supported by target array. | def _choose_rest_version(self):
"""Return the newest REST API version supported by target array."""
versions = self._list_available_rest_versions()
versions = [LooseVersion(x) for x in versions if x in self.supported_rest_versions]
if versions:
return max(versions)
el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.