Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _parse_kexgss_hostkey(self, m): # client mode host_key = m.get_string() self.transport.host_key = host_key sig = m.get_string() self.transport._verify_key(host_key, sig) self.transport._expect_packet(MSG_KEXGSS_CON...
[ "\n Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode).\n\n :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message\n " ]
Please provide a description of the function:def _parse_kexgss_continue(self, m): if not self.transport.server_mode: srv_token = m.get_string() m = Message() m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string( self.kexgss.ssh_init_sec_context(...
[ "\n Parse the SSH2_MSG_KEXGSS_CONTINUE message.\n\n :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE\n message\n " ]
Please provide a description of the function:def _parse_kexgss_complete(self, m): # client mode if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() if (self.f < 1) or (self.f > self.P - 1): raise SSHException...
[ "\n Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode).\n\n :param `.Message` m: The content of the\n SSH2_MSG_KEXGSS_COMPLETE message\n " ]
Please provide a description of the function:def _parse_kexgss_init(self, m): # server mode client_token = m.get_string() self.e = m.get_mpint() if (self.e < 1) or (self.e > self.P - 1): raise SSHException('Client kex "e" is out of range') K = pow(self.e, sel...
[ "\n Parse the SSH2_MSG_KEXGSS_INIT message (server mode).\n\n :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message\n " ]
Please provide a description of the function:def start_kex(self): 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 # (preferred_bits). according to the ...
[ "\n Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange\n " ]
Please provide a description of the function:def parse_next(self, ptype, m): if ptype == MSG_KEXGSS_GROUPREQ: return self._parse_kexgss_groupreq(m) elif ptype == MSG_KEXGSS_GROUP: return self._parse_kexgss_group(m) elif ptype == MSG_KEXGSS_INIT: retur...
[ "\n Parse the next packet.\n\n :param ptype: The (string) type of the incoming packet\n :param `.Message` m: The paket content\n " ]
Please provide a description of the function:def _parse_kexgss_group(self, m): self.p = m.get_mpint() self.g = m.get_mpint() # reject if p's bit length < 1024 or > 8192 bitlen = util.bit_length(self.p) if (bitlen < 1024) or (bitlen > 8192): raise SSHException...
[ "\n Parse the SSH2_MSG_KEXGSS_GROUP message (client mode).\n\n :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message\n " ]
Please provide a description of the function:def _parse_kexgss_complete(self, m): if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this me...
[ "\n Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode).\n\n :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message\n " ]
Please provide a description of the function:def _parse_kexgss_error(self, m): maj_status = m.get_int() min_status = m.get_int() err_msg = m.get_string() m.get_string() # we don't care about the language (lang_tag)! raise SSHException( .format( ...
[ "\n Parse the SSH2_MSG_KEXGSS_ERROR message (client mode).\n The server may send a GSS-API error message. if it does, we display\n the error by throwing an exception (client mode).\n\n :param `Message` m: The content of the SSH2_MSG_KEXGSS_ERROR message\n :raise SSHException: Con...
Please provide a description of the function:def from_stat(cls, obj, filename=None): attr = cls() attr.st_size = obj.st_size attr.st_uid = obj.st_uid attr.st_gid = obj.st_gid attr.st_mode = obj.st_mode attr.st_atime = obj.st_atime attr.st_mtime = obj.st_m...
[ "\n Create an `.SFTPAttributes` object from an existing ``stat`` object (an\n object returned by `os.stat`).\n\n :param object obj: an object returned by `os.stat` (or equivalent).\n :param str filename: the filename associated with this file.\n :return: new `.SFTPAttributes` obje...
Please provide a description of the function:def generate(bits, progress_func=None): key = rsa.generate_private_key( public_exponent=65537, key_size=bits, backend=default_backend() ) return RSAKey(key=key)
[ "\n Generate a new private RSA key. This factory function can be used to\n generate a new host key or authentication key.\n\n :param int bits: number of bits the generated key should be.\n :param progress_func: Unused\n :return: new `.RSAKey` private key\n " ]
Please provide a description of the function:def _data_in_prefetch_buffers(self, offset): k = [i for i in self._prefetch_data.keys() if i <= offset] if len(k) == 0: return None index = max(k) buf_offset = offset - index if buf_offset >= len(self._prefetch_dat...
[ "\n if a block of data is present in the prefetch buffers, at the given\n offset, return the offset of the relevant prefetch buffer. otherwise,\n return None. this guarantees nothing about the number of bytes\n collected in the prefetch buffer so far.\n " ]
Please provide a description of the function:def seek(self, offset, whence=0): self.flush() if whence == self.SEEK_SET: self._realpos = self._pos = offset elif whence == self.SEEK_CUR: self._pos += offset self._realpos = self._pos else: ...
[ "\n Set the file's current position.\n\n See `file.seek` for details.\n " ]
Please provide a description of the function:def stat(self): t, msg = self.sftp._request(CMD_FSTAT, self.handle) if t != CMD_ATTRS: raise SFTPError("Expected attributes") return SFTPAttributes._from_msg(msg)
[ "\n Retrieve information about this file from the remote system. This is\n exactly like `.SFTPClient.stat`, except that it operates on an\n already-open file.\n\n :returns:\n an `.SFTPAttributes` object containing attributes about this file.\n " ]
Please provide a description of the function:def truncate(self, size): self.sftp._log( DEBUG, "truncate({}, {!r})".format(hexlify(self.handle), size) ) attr = SFTPAttributes() attr.st_size = size self.sftp._request(CMD_FSETSTAT, self.handle, attr)
[ "\n Change the size of this file. This usually extends\n or shrinks the size of the file, just like the ``truncate()`` method on\n Python file objects.\n\n :param size: the new size of the file\n " ]
Please provide a description of the function:def check(self, hash_algorithm, offset=0, length=0, block_size=0): t, msg = self.sftp._request( CMD_EXTENDED, "check-file", self.handle, hash_algorithm, long(offset), long(length), ...
[ "\n Ask the server for a hash of a section of this file. This can be used\n to verify a successful upload or download, or for various rsync-like\n operations.\n\n The file is hashed from ``offset``, for ``length`` bytes.\n If ``length`` is 0, the remainder of the file is hashed. ...
Please provide a description of the function:def prefetch(self, file_size=None): if file_size is None: file_size = self.stat().st_size # queue up async reads for the rest of the file chunks = [] n = self._realpos while n < file_size: chunk = min(...
[ "\n Pre-fetch the remaining contents of this file in anticipation of future\n `.read` calls. If reading the entire file, pre-fetching can\n dramatically improve the download speed by avoiding roundtrip latency.\n The file's contents are incrementally buffered in a background thread.\n\n...
Please provide a description of the function:def readv(self, chunks): self.sftp._log( DEBUG, "readv({}, {!r})".format(hexlify(self.handle), chunks) ) read_chunks = [] for offset, size in chunks: # don't fetch data that's already in the prefetch buffer ...
[ "\n Read a set of blocks from the file by (offset, length). This is more\n efficient than doing a series of `.seek` and `.read` calls, since the\n prefetch machinery is used to retrieve all the requested blocks at\n once.\n\n :param chunks:\n a list of ``(offset, lengt...
Please provide a description of the function:def _check_exception(self): if self._saved_exception is not None: x = self._saved_exception self._saved_exception = None raise x
[ "if there's a saved exception, raise & clear it" ]
Please provide a description of the function:def open_only(func): @wraps(func) def _check(self, *args, **kwds): if ( self.closed or self.eof_received or self.eof_sent or not self.active ): raise SSHException("Channel is not open")...
[ "\n Decorator for `.Channel` methods which performs an openness check.\n\n :raises:\n `.SSHException` -- If the wrapped method is called on an unopened\n `.Channel`.\n " ]
Please provide a description of the function:def exec_command(self, command): m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("exec") m.add_boolean(True) m.add_string(command) self._event_pending() self.tr...
[ "\n Execute a command on the server. If the server allows it, the channel\n will then be directly connected to the stdin, stdout, and stderr of\n the command being executed.\n\n When the command finishes executing, the channel will be closed and\n can't be reused. You must open ...
Please provide a description of the function:def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("window-change") m.add_boolean(False) m.add_int(widt...
[ "\n Resize the pseudo-terminal. This can be used to change the width and\n height of the terminal emulation created in a previous `get_pty` call.\n\n :param int width: new width (in characters) of the terminal screen\n :param int height: new height (in characters) of the terminal screen...
Please provide a description of the function:def update_environment(self, environment): for name, value in environment.items(): try: self.set_environment_variable(name, value) except SSHException as e: err = 'Failed to set environment variable "{}...
[ "\n Updates this channel's remote shell environment.\n\n .. note::\n This operation is additive - i.e. the current environment is not\n reset before the given environment variables are set.\n\n .. warning::\n Servers may silently reject some environment variable...
Please provide a description of the function:def set_environment_variable(self, name, value): m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("env") m.add_boolean(False) m.add_string(name) m.add_string(value) ...
[ "\n Set the value of an environment variable.\n\n .. warning::\n The server may reject this request depending on its ``AcceptEnv``\n setting; such rejections will fail silently (which is common client\n practice for this particular request type). Make sure you\n ...
Please provide a description of the function:def recv_exit_status(self): self.status_event.wait() assert self.status_event.is_set() return self.exit_status
[ "\n Return the exit status from the process on the server. This is\n mostly useful for retrieving the results of an `exec_command`.\n If the command hasn't finished yet, this method will wait until\n it does, or until the channel is closed. If no exit status is\n provided by the...
Please provide a description of the function:def request_x11( self, screen_number=0, auth_protocol=None, auth_cookie=None, single_connection=False, handler=None, ): if auth_protocol is None: auth_protocol = "MIT-MAGIC-COOKIE-1" if ...
[ "\n Request an x11 session on this channel. If the server allows it,\n further x11 requests can be made from the server to the client,\n when an x11 application is run in a shell session.\n\n From :rfc:`4254`::\n\n It is RECOMMENDED that the 'x11 authentication cookie' that i...
Please provide a description of the function:def request_forward_agent(self, handler): m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("auth-agent-req@openssh.com") m.add_boolean(False) self.transport._send_user_message(m...
[ "\n Request for a forward SSH Agent on this channel.\n This is only valid for an ssh-agent from OpenSSH !!!\n\n :param handler:\n a required callable handler to use for incoming SSH Agent\n connections\n\n :return: True if we are ok, else False\n (at that...
Please provide a description of the function:def set_combine_stderr(self, combine): data = bytes() self.lock.acquire() try: old = self.combine_stderr self.combine_stderr = combine if combine and not old: # copy old stderr buffer into p...
[ "\n Set whether stderr should be combined into stdout on this channel.\n The default is ``False``, but in some cases it may be convenient to\n have both streams combined.\n\n If this is ``False``, and `exec_command` is called (or ``invoke_shell``\n with no pty), output to stderr w...
Please provide a description of the function:def close(self): self.lock.acquire() try: # only close the pipe when the user explicitly closes the channel. # otherwise they will get unpleasant surprises. (and do it before # checking self.closed, since the remo...
[ "\n Close the channel. All future read/write operations on the channel\n will fail. The remote end will receive no more data (after queued data\n is flushed). Channels are automatically closed when their `.Transport`\n is closed or when they are garbage collected.\n " ]
Please provide a description of the function:def send_ready(self): self.lock.acquire() try: if self.closed or self.eof_sent: return True return self.out_window_size > 0 finally: self.lock.release()
[ "\n Returns true if data can be written to this channel without blocking.\n This means the channel is either closed (so any write attempt would\n return immediately) or there is at least one byte of space in the\n outbound buffer. If there is at least one byte of space in the\n ou...
Please provide a description of the function:def send(self, s): m = Message() m.add_byte(cMSG_CHANNEL_DATA) m.add_int(self.remote_chanid) return self._send(s, m)
[ "\n Send data to the channel. Returns the number of bytes sent, or 0 if\n the channel stream is closed. Applications are responsible for\n checking that all data has been sent: if only some of the data was\n transmitted, the application needs to attempt delivery of the remaining\n ...
Please provide a description of the function:def send_stderr(self, s): m = Message() m.add_byte(cMSG_CHANNEL_EXTENDED_DATA) m.add_int(self.remote_chanid) m.add_int(1) return self._send(s, m)
[ "\n Send data to the channel on the \"stderr\" stream. This is normally\n only used by servers to send output from shell commands -- clients\n won't use this. Returns the number of bytes sent, or 0 if the channel\n stream is closed. Applications are responsible for checking that all\n...
Please provide a description of the function:def sendall(self, s): while s: sent = self.send(s) s = s[sent:] return None
[ "\n Send data to the channel, without allowing partial results. Unlike\n `send`, this method continues to send data from the given string until\n either all data has been sent or an error occurs. Nothing is returned.\n\n :param str s: data to send.\n\n :raises socket.timeout:\n ...
Please provide a description of the function:def sendall_stderr(self, s): while s: sent = self.send_stderr(s) s = s[sent:] return None
[ "\n Send data to the channel's \"stderr\" stream, without allowing partial\n results. Unlike `send_stderr`, this method continues to send data\n from the given string until all data has been sent or an error occurs.\n Nothing is returned.\n\n :param str s: data to send to the cli...
Please provide a description of the function:def fileno(self): self.lock.acquire() try: if self._pipe is not None: return self._pipe.fileno() # create the pipe and feed in any existing data self._pipe = pipe.make_pipe() p1, p2 = pi...
[ "\n Returns an OS-level file descriptor which can be used for polling, but\n but not for reading or writing. This is primarily to allow Python's\n ``select`` module to work.\n\n The first time ``fileno`` is called on a channel, a pipe is created to\n simulate real OS-level file d...
Please provide a description of the function:def shutdown(self, how): if (how == 0) or (how == 2): # feign "read" shutdown self.eof_received = 1 if (how == 1) or (how == 2): self.lock.acquire() try: m = self._send_eof() ...
[ "\n Shut down one or both halves of the connection. If ``how`` is 0,\n further receives are disallowed. If ``how`` is 1, further sends\n are disallowed. If ``how`` is 2, further sends and receives are\n disallowed. This closes the stream in one or both directions.\n\n :param i...
Please provide a description of the function:def _wait_for_send_window(self, size): # you are already holding the lock if self.closed or self.eof_sent: return 0 if self.out_window_size == 0: # should we block? if self.timeout == 0.0: r...
[ "\n (You are already holding the lock.)\n Wait for the send window to open up, and allocate up to ``size`` bytes\n for transmission. If no space opens up before the timeout, a timeout\n exception is raised. Returns the number of bytes available to send\n (may be less than reques...
Please provide a description of the function:def convert_errno(e): if e == errno.EACCES: # permission denied return SFTP_PERMISSION_DENIED elif (e == errno.ENOENT) or (e == errno.ENOTDIR): # no such file return SFTP_NO_SUCH_FILE else: ...
[ "\n Convert an errno value (as from an ``OSError`` or ``IOError``) into a\n standard SFTP result code. This is a convenience function for trapping\n exceptions in server code and returning an appropriate result.\n\n :param int e: an errno code, as from ``OSError.errno``.\n :retur...
Please provide a description of the function:def _convert_pflags(self, pflags): 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_RDONLY if pfla...
[ "convert SFTP-style open() flags to Python's os.open() flags" ]
Please provide a description of the function:def set_event(self, event): self._lock.acquire() try: self._event = event # Make sure the event starts in `set` state if we appear to already # be closed; otherwise, if we start in `clear` state & are closed, ...
[ "\n Set an event on this buffer. When data is ready to be read (or the\n buffer has been closed), the event will be set. When no data is\n ready, the event will be cleared.\n\n :param threading.Event event: the event to set/clear\n " ]
Please provide a description of the function:def feed(self, data): self._lock.acquire() try: if self._event is not None: self._event.set() self._buffer_frombytes(b(data)) self._cv.notifyAll() finally: self._lock.release()
[ "\n Feed new data into this pipe. This method is assumed to be called\n from a separate thread, so synchronization is done.\n\n :param data: the data to add, as a ``str`` or ``bytes``\n " ]
Please provide a description of the function:def read_ready(self): self._lock.acquire() try: if len(self._buffer) == 0: return False return True finally: self._lock.release()
[ "\n Returns true if data is buffered and ready to be read from this\n feeder. A ``False`` result does not mean that the feeder has closed;\n it means you may need to wait before more data arrives.\n\n :return:\n ``True`` if a `read` call would immediately return at least one\...
Please provide a description of the function:def read(self, nbytes, timeout=None): out = bytes() self._lock.acquire() try: if len(self._buffer) == 0: if self._closed: return out # should we block? if timeout...
[ "\n Read data from the pipe. The return value is a string representing\n the data received. The maximum amount of data to be received at once\n is specified by ``nbytes``. If a string of length zero is returned,\n the pipe has been closed.\n\n The optional ``timeout`` argument ...
Please provide a description of the function:def empty(self): self._lock.acquire() try: out = self._buffer_tobytes() del self._buffer[:] if (self._event is not None) and not self._closed: self._event.clear() return out fina...
[ "\n Clear out the buffer and return all data that was in it.\n\n :return:\n any data that was in the buffer prior to clearing it out, as a\n `str`\n " ]
Please provide a description of the function:def close(self): self._lock.acquire() try: self._closed = True self._cv.notifyAll() if self._event is not None: self._event.set() finally: self._lock.release()
[ "\n Close this pipe object. Future calls to `read` after the buffer\n has been emptied will return immediately with an empty string.\n " ]
Please provide a description of the function:def parse(self, file_obj): host = {"host": ["*"], "config": {}} for line in file_obj: # Strip any leading or trailing whitespace from the line. # Refer to https://github.com/paramiko/paramiko/issues/499 line = line...
[ "\n Read an OpenSSH config from the given file object.\n\n :param file_obj: a file-like object to read the config file from\n " ]
Please provide a description of the function:def lookup(self, hostname): matches = [ config for config in self._config if self._allowed(config["host"], hostname) ] ret = SSHConfigDict() for match in matches: for key, value in matc...
[ "\n Return a dict (`SSHConfigDict`) of config options for a given hostname.\n\n The host-matching rules of OpenSSH's ``ssh_config`` man page are used:\n For each parameter, the first obtained value will be used. The\n configuration files contain sections separated by ``Host``\n s...
Please provide a description of the function:def get_hostnames(self): hosts = set() for entry in self._config: hosts.update(entry["host"]) return hosts
[ "\n Return the set of literal hostnames defined in the SSH config (both\n explicit hostnames and wildcard entries).\n " ]
Please provide a description of the function:def _expand_variables(self, config, hostname): if "hostname" in config: config["hostname"] = config["hostname"].replace("%h", hostname) else: config["hostname"] = hostname if "port" in config: port = conf...
[ "\n Return a dict of config options with expanded substitutions\n for a given hostname.\n\n Please refer to man ``ssh_config`` for the parameters that\n are replaced.\n\n :param dict config: the config for the hostname\n :param str hostname: the hostname that the config bel...
Please provide a description of the function:def _get_hosts(self, host): try: return shlex.split(host) except ValueError: raise Exception("Unparsable host {}".format(host))
[ "\n Return a list of host_names from host value.\n " ]
Please provide a description of the function:def as_bool(self, key): val = self[key] if isinstance(val, bool): return val return val.lower() == "yes"
[ "\n Express given key's value as a boolean type.\n\n Typically, this is used for ``ssh_config``'s pseudo-boolean values\n which are either ``\"yes\"`` or ``\"no\"``. In such cases, ``\"yes\"`` yields\n ``True`` and any other value becomes ``False``.\n\n .. note::\n If (...
Please provide a description of the function:def check_auth_gssapi_with_mic( self, username, gss_authenticated=AUTH_FAILED, cc_file=None ): if gss_authenticated == AUTH_SUCCESSFUL: return AUTH_SUCCESSFUL return AUTH_FAILED
[ "\n Authenticate the given user to the server if he is a valid krb5\n principal.\n\n :param str username: The username of the authenticating client\n :param int gss_authenticated: The result of the krb5 authentication\n :param str cc_filename: The krb5 client credentials cache fil...
Please provide a description of the function:def check_auth_gssapi_keyex( self, username, gss_authenticated=AUTH_FAILED, cc_file=None ): if gss_authenticated == AUTH_SUCCESSFUL: return AUTH_SUCCESSFUL return AUTH_FAILED
[ "\n Authenticate the given user to the server if he is a valid krb5\n principal and GSS-API Key Exchange was performed.\n If GSS-API Key Exchange was not performed, this authentication method\n won't be available.\n\n :param str username: The username of the authenticating client\...
Please provide a description of the function:def check_channel_subsystem_request(self, channel, name): transport = channel.get_transport() handler_class, larg, kwarg = transport._get_subsystem_handler(name) if handler_class is None: return False handler = handler_cla...
[ "\n Determine if a requested subsystem will be provided to the client on\n the given channel. If this method returns ``True``, all future I/O\n through this channel will be assumed to be connected to the requested\n subsystem. An example of a subsystem is ``sftp``.\n\n The defau...
Please provide a description of the function:def add_prompt(self, prompt, echo=True): self.prompts.append((prompt, echo))
[ "\n Add a prompt to this query. The prompt should be a (reasonably short)\n string. Multiple prompts can be added to the same query.\n\n :param str prompt: the user prompt\n :param bool echo:\n ``True`` (default) if the user's response should be echoed;\n ``False`...
Please provide a description of the function:def GSSAuth(auth_method, gss_deleg_creds=True): if _API == "MIT": return _SSH_GSSAPI(auth_method, gss_deleg_creds) elif _API == "SSPI" and os.name == "nt": return _SSH_SSPI(auth_method, gss_deleg_creds) else: raise ImportError("Unable...
[ "\n Provide SSH2 GSS-API / SSPI authentication.\n\n :param str auth_method: The name of the SSH authentication mechanism\n (gssapi-with-mic or gss-keyex)\n :param bool gss_deleg_creds: Delegate client credentials or not.\n We delegate credentials b...
Please provide a description of the function:def ssh_gss_oids(self, mode="client"): from pyasn1.type.univ import ObjectIdentifier from pyasn1.codec.der import encoder OIDs = self._make_uint32(1) krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech)) OID_len = self...
[ "\n This method returns a single OID, because we only support the\n Kerberos V5 mechanism.\n\n :param str mode: Client for client mode and server for server mode\n :return: A byte sequence containing the number of supported\n OIDs, the length of the OID and the actual OID...
Please provide a description of the function:def ssh_check_mech(self, desired_mech): from pyasn1.codec.der import decoder mech, __ = decoder.decode(desired_mech) if mech.__str__() != self._krb5_mech: return False return True
[ "\n Check if the given OID is the Kerberos V5 OID (server mode).\n\n :param str desired_mech: The desired GSS-API mechanism of the client\n :return: ``True`` if the given OID is supported, otherwise C{False}\n " ]
Please provide a description of the function:def _ssh_build_mic(self, session_id, username, service, auth_method): mic = self._make_uint32(len(session_id)) mic += session_id mic += struct.pack("B", MSG_USERAUTH_REQUEST) mic += self._make_uint32(len(username)) mic += user...
[ "\n Create the SSH2 MIC filed for gssapi-with-mic.\n\n :param str session_id: The SSH session ID\n :param str username: The name of the user who attempts to login\n :param str service: The requested SSH service\n :param str auth_method: The requested SSH authentication mechanism\n...
Please provide a description of the function:def ssh_init_sec_context( self, target, desired_mech=None, username=None, recv_token=None ): from pyasn1.codec.der import decoder self._username = username self._gss_host = target targ_name = gssapi.Name( "hos...
[ "\n Initialize a GSS-API context.\n\n :param str username: The name of the user who attempts to login\n :param str target: The hostname of the target to connect to\n :param str desired_mech: The negotiated GSS-API mechanism\n (\"pseudo negotiated\" mechani...
Please provide a description of the function:def ssh_accept_sec_context(self, hostname, recv_token, username=None): # hostname and username are not required for GSSAPI, but for SSPI self._gss_host = hostname self._username = username if self._gss_srv_ctxt is None: se...
[ "\n Accept a GSS-API context (server mode).\n\n :param str hostname: The servers hostname\n :param str username: The name of the user who attempts to login\n :param str recv_token: The GSS-API Token received from the server,\n if it's not the initial call.\n...
Please provide a description of the function:def ssh_init_sec_context( self, target, desired_mech=None, username=None, recv_token=None ): from pyasn1.codec.der import decoder self._username = username self._gss_host = target error = 0 targ_name = "host/" + s...
[ "\n Initialize a SSPI context.\n\n :param str username: The name of the user who attempts to login\n :param str target: The FQDN of the target to connect to\n :param str desired_mech: The negotiated SSPI mechanism\n (\"pseudo negotiated\" mechanism, becaus...
Please provide a description of the function:def ssh_get_mic(self, session_id, gss_kex=False): self._session_id = session_id if not gss_kex: mic_field = self._ssh_build_mic( self._session_id, self._username, self._service, ...
[ "\n Create the MIC token for a SSH2 message.\n\n :param str session_id: The SSH session ID\n :param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not\n :return: gssapi-with-mic:\n Returns the MIC token from SSPI for the message we created\n ...
Please provide a description of the function:def ssh_accept_sec_context(self, hostname, username, recv_token): self._gss_host = hostname self._username = username targ_name = "host/" + self._gss_host self._gss_srv_ctxt = sspi.ServerAuth("Kerberos", spn=targ_name) error, ...
[ "\n Accept a SSPI context (server mode).\n\n :param str hostname: The servers FQDN\n :param str username: The name of the user who attempts to login\n :param str recv_token: The SSPI Token received from the server,\n if it's not the initial call.\n :r...
Please provide a description of the function:def ssh_check_mic(self, mic_token, session_id, username=None): self._session_id = session_id self._username = username if username is not None: # server mode mic_field = self._ssh_build_mic( self._sessi...
[ "\n Verify the MIC token for a SSH2 message.\n\n :param str mic_token: The MIC token received from the client\n :param str session_id: The SSH session ID\n :param str username: The name of the user who attempts to login\n :return: None if the MIC check was successful\n :rai...
Please provide a description of the function:def credentials_delegated(self): return self._gss_flags & sspicon.ISC_REQ_DELEGATE and ( self._gss_srv_ctxt_status or self._gss_flags )
[ "\n Checks if credentials are delegated (server mode).\n\n :return: ``True`` if credentials are delegated, otherwise ``False``\n " ]
Please provide a description of the function:def from_transport(cls, t, window_size=None, max_packet_size=None): chan = t.open_session( window_size=window_size, max_packet_size=max_packet_size ) if chan is None: return None chan.invoke_subsystem("sftp") ...
[ "\n Create an SFTP client channel from an open `.Transport`.\n\n Setting the window and packet sizes might affect the transfer speed.\n The default settings in the `.Transport` class are the same as in\n OpenSSH and should work adequately for both files transfers and\n interactive...
Please provide a description of the function:def listdir_iter(self, path=".", read_aheads=50): path = self._adjust_cwd(path) self._log(DEBUG, "listdir({!r})".format(path)) t, msg = self._request(CMD_OPENDIR, path) if t != CMD_HANDLE: raise SFTPError("Expected handle...
[ "\n Generator version of `.listdir_attr`.\n\n See the API docs for `.listdir_attr` for overall details.\n\n This function adds one more kwarg on top of `.listdir_attr`:\n ``read_aheads``, an integer controlling how many\n ``SSH_FXP_READDIR`` requests are made to the server. The de...
Please provide a description of the function:def rename(self, oldpath, newpath): oldpath = self._adjust_cwd(oldpath) newpath = self._adjust_cwd(newpath) self._log(DEBUG, "rename({!r}, {!r})".format(oldpath, newpath)) self._request(CMD_RENAME, oldpath, newpath)
[ "\n Rename a file or folder from ``oldpath`` to ``newpath``.\n\n .. note::\n This method implements 'standard' SFTP ``RENAME`` behavior; those\n seeking the OpenSSH \"POSIX rename\" extension behavior should use\n `posix_rename`.\n\n :param str oldpath:\n ...
Please provide a description of the function:def posix_rename(self, oldpath, newpath): oldpath = self._adjust_cwd(oldpath) newpath = self._adjust_cwd(newpath) self._log(DEBUG, "posix_rename({!r}, {!r})".format(oldpath, newpath)) self._request( CMD_EXTENDED, "posix-re...
[ "\n Rename a file or folder from ``oldpath`` to ``newpath``, following\n posix conventions.\n\n :param str oldpath: existing name of the file or folder\n :param str newpath: new name for the file or folder, will be\n overwritten if it already exists\n\n :raises:\n ...
Please provide a description of the function:def mkdir(self, path, mode=o777): path = self._adjust_cwd(path) self._log(DEBUG, "mkdir({!r}, {!r})".format(path, mode)) attr = SFTPAttributes() attr.st_mode = mode self._request(CMD_MKDIR, path, attr)
[ "\n Create a folder (directory) named ``path`` with numeric mode ``mode``.\n The default mode is 0777 (octal). On some systems, mode is ignored.\n Where it is used, the current umask value is first masked out.\n\n :param str path: name of the folder to create\n :param int mode: p...
Please provide a description of the function:def symlink(self, source, dest): dest = self._adjust_cwd(dest) self._log(DEBUG, "symlink({!r}, {!r})".format(source, dest)) source = b(source) self._request(CMD_SYMLINK, source, dest)
[ "\n Create a symbolic link to the ``source`` path at ``destination``.\n\n :param str source: path of the original file\n :param str dest: path of the newly created symlink\n " ]
Please provide a description of the function:def chown(self, path, uid, gid): path = self._adjust_cwd(path) self._log(DEBUG, "chown({!r}, {!r}, {!r})".format(path, uid, gid)) attr = SFTPAttributes() attr.st_uid, attr.st_gid = uid, gid self._request(CMD_SETSTAT, path, att...
[ "\n Change the owner (``uid``) and group (``gid``) of a file. As with\n Python's `os.chown` function, you must pass both arguments, so if you\n only want to change one, use `stat` first to retrieve the current\n owner and group.\n\n :param str path: path of the file to change the...
Please provide a description of the function:def utime(self, path, times): path = self._adjust_cwd(path) if times is None: times = (time.time(), time.time()) self._log(DEBUG, "utime({!r}, {!r})".format(path, times)) attr = SFTPAttributes() attr.st_atime, attr...
[ "\n Set the access and modified times of the file specified by ``path``.\n If ``times`` is ``None``, then the file's access and modified times\n are set to the current time. Otherwise, ``times`` must be a 2-tuple\n of numbers, of the form ``(atime, mtime)``, which is used to set the\n ...
Please provide a description of the function:def truncate(self, path, size): path = self._adjust_cwd(path) self._log(DEBUG, "truncate({!r}, {!r})".format(path, size)) attr = SFTPAttributes() attr.st_size = size self._request(CMD_SETSTAT, path, attr)
[ "\n Change the size of the file specified by ``path``. This usually\n extends or shrinks the size of the file, just like the `~file.truncate`\n method on Python file objects.\n\n :param str path: path of the file to modify\n :param int size: the new size of the file\n " ]
Please provide a description of the function:def putfo(self, fl, remotepath, file_size=0, callback=None, confirm=True): with self.file(remotepath, "wb") as fr: fr.set_pipelined(True) size = self._transfer_with_callback( reader=fl, writer=fr, file_size=file_size, ...
[ "\n Copy the contents of an open file object (``fl``) to the SFTP server as\n ``remotepath``. Any exception raised by operations will be passed\n through.\n\n The SFTP operations use pipelining for speed.\n\n :param fl: opened file or file-like object to copy\n :param str r...
Please provide a description of the function:def put(self, localpath, remotepath, callback=None, confirm=True): file_size = os.stat(localpath).st_size with open(localpath, "rb") as fl: return self.putfo(fl, remotepath, file_size, callback, confirm)
[ "\n Copy a local file (``localpath``) to the SFTP server as ``remotepath``.\n Any exception raised by operations will be passed through. This\n method is primarily provided as a convenience.\n\n The SFTP operations use pipelining for speed.\n\n :param str localpath: the local fil...
Please provide a description of the function:def getfo(self, remotepath, fl, callback=None): file_size = self.stat(remotepath).st_size with self.open(remotepath, "rb") as fr: fr.prefetch(file_size) return self._transfer_with_callback( reader=fr, writer=fl...
[ "\n Copy a remote file (``remotepath``) from the SFTP server and write to\n an open file or file-like object, ``fl``. Any exception raised by\n operations will be passed through. This method is primarily provided\n as a convenience.\n\n :param object remotepath: opened file or f...
Please provide a description of the function:def get(self, remotepath, localpath, callback=None): with open(localpath, "wb") as fl: size = self.getfo(remotepath, fl, callback) s = os.stat(localpath) if s.st_size != size: raise IOError( "size misma...
[ "\n Copy a remote file (``remotepath``) from the SFTP server to the local\n host as ``localpath``. Any exception raised by operations will be\n passed through. This method is primarily provided as a convenience.\n\n :param str remotepath: the remote file to copy\n :param str loc...
Please provide a description of the function:def _convert_status(self, msg): code = msg.get_int() text = msg.get_text() if code == SFTP_OK: return elif code == SFTP_EOF: raise EOFError(text) elif code == SFTP_NO_SUCH_FILE: # clever ide...
[ "\n Raises EOFError or IOError on error status; otherwise does nothing.\n " ]
Please provide a description of the function:def _adjust_cwd(self, path): path = b(path) if self._cwd is None: return path if len(path) and path[0:1] == b_slash: # absolute path return path if self._cwd == b_slash: return self._cwd...
[ "\n Return an adjusted path if we're emulating a \"current working\n directory\" for the server.\n " ]
Please provide a description of the function:def coverage(ctx, opts=""): return test(ctx, coverage=True, include_slow=True, opts=opts)
[ "\n Execute all tests (normal and slow) with coverage enabled.\n " ]
Please provide a description of the function:def guard(ctx, opts=""): # TODO if coverage was run via pytest-cov, we could add coverage here too return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
[ "\n Execute all tests and then watch for changes, re-running.\n " ]
Please provide a description of the function:def release(ctx, sdist=True, wheel=True, sign=True, dry_run=False, index=None): # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs", pty=True, hide=False) # Move the built docs into where Epydocs used to live target = "docs...
[ "\n Wraps invocations.packaging.publish to add baked-in docs folder.\n " ]
Please provide a description of the function:def set_gss_host(self, gss_host, trust_dns=True, gssapi_requested=True): # No GSSAPI in play == nothing to do if not gssapi_requested: return # Obtain the correct host first - did user request a GSS-specific name # to use ...
[ "\n Normalize/canonicalize ``self.gss_host`` depending on various factors.\n\n :param str gss_host:\n The explicitly requested GSS-oriented hostname to connect to (i.e.\n what the host's name is in the Kerberos database.) Defaults to\n ``self.hostname`` (which will be ...
Please provide a description of the function:def start_client(self, event=None, timeout=None): self.active = True if event is not None: # async, return immediately and let the app poll for completion self.completion_event = event self.start() retu...
[ "\n Negotiate a new SSH2 session as a client. This is the first step after\n creating a new `.Transport`. A separate thread is created for protocol\n negotiation.\n\n If an event is passed in, this method returns immediately. When\n negotiation is done (successful or not), the ...
Please provide a description of the function:def load_server_moduli(filename=None): Transport._modulus_pack = ModulusPack() # places to look for the openssh "moduli" file file_list = ["/etc/ssh/moduli", "/usr/local/etc/moduli"] if filename is not None: file_list.inse...
[ "\n (optional)\n Load a file of prime moduli for use in doing group-exchange key\n negotiation in server mode. It's a rather obscure option and can be\n safely ignored.\n\n In server mode, the remote client may request \"group-exchange\" key\n negotiation, which asks the s...
Please provide a description of the function:def close(self): if not self.active: return self.stop_thread() for chan in list(self._channels.values()): chan._unlink() self.sock.close()
[ "\n Close this session, and any open channels that are tied to it.\n " ]
Please provide a description of the function:def open_session( self, window_size=None, max_packet_size=None, timeout=None ): return self.open_channel( "session", window_size=window_size, max_packet_size=max_packet_size, timeout=timeout, ...
[ "\n Request a new channel to the server, of type ``\"session\"``. This is\n just an alias for calling `open_channel` with an argument of\n ``\"session\"``.\n\n .. note:: Modifying the the window and packet sizes might have adverse\n effects on the session created. The default...
Please provide a description of the function:def open_channel( self, kind, dest_addr=None, src_addr=None, window_size=None, max_packet_size=None, timeout=None, ): if not self.active: raise SSHException("SSH session not active") ...
[ "\n Request a new channel to the server. `Channels <.Channel>` are\n socket-like objects used for the actual transfer of data across the\n session. You may only request a channel after negotiating encryption\n (using `connect` or `start_client`) and authenticating.\n\n .. note:: M...
Please provide a description of the function:def request_port_forward(self, address, port, handler=None): if not self.active: raise SSHException("SSH session not active") port = int(port) response = self.global_request( "tcpip-forward", (address, port), wait=True...
[ "\n Ask the server to forward TCP connections from a listening port on\n the server, across this SSH session.\n\n If a handler is given, that handler is called from a different thread\n whenever a forwarded connection arrives. The handler parameters are::\n\n handler(\n ...
Please provide a description of the function:def cancel_port_forward(self, address, port): if not self.active: return self._tcp_handler = None self.global_request("cancel-tcpip-forward", (address, port), wait=True)
[ "\n Ask the server to cancel a previous port-forwarding request. No more\n connections to the given address & port will be forwarded across this\n ssh connection.\n\n :param str address: the address to stop forwarding\n :param int port: the port to stop forwarding\n " ]
Please provide a description of the function:def send_ignore(self, byte_count=None): m = Message() m.add_byte(cMSG_IGNORE) if byte_count is None: byte_count = (byte_ord(os.urandom(1)) % 32) + 10 m.add_bytes(os.urandom(byte_count)) self._send_user_message(m)
[ "\n Send a junk packet across the encrypted link. This is sometimes used\n to add \"noise\" to a connection to confuse would-be attackers. It can\n also be used as a keep-alive for long lived connections traversing\n firewalls.\n\n :param int byte_count:\n the number ...
Please provide a description of the function:def accept(self, timeout=None): self.lock.acquire() try: if len(self.server_accepts) > 0: chan = self.server_accepts.pop(0) else: self.server_accept_cv.wait(timeout) if len(self....
[ "\n Return the next channel opened by the client over this transport, in\n server mode. If no channel is opened before the given timeout,\n ``None`` is returned.\n\n :param int timeout:\n seconds to wait for a channel, or ``None`` to wait forever\n :return: a new `.Cha...
Please provide a description of the function:def connect( self, hostkey=None, username="", password=None, pkey=None, gss_host=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, gss_trust_dns=True, ): if hostkey ...
[ "\n Negotiate an SSH2 session, and optionally verify the server's host key\n and authenticate using a password or private key. This is a shortcut\n for `start_client`, `get_remote_server_key`, and\n `Transport.auth_password` or `Transport.auth_publickey`. Use those\n methods if ...
Please provide a description of the function:def get_exception(self): self.lock.acquire() try: e = self.saved_exception self.saved_exception = None return e finally: self.lock.release()
[ "\n Return any exception that happened during the last server request.\n This can be used to fetch more specific error information after using\n calls like `start_client`. The exception (if any) is cleared after\n this call.\n\n :return:\n an exception, or ``None`` if ...
Please provide a description of the function:def set_subsystem_handler(self, name, handler, *larg, **kwarg): try: self.lock.acquire() self.subsystem_table[name] = (handler, larg, kwarg) finally: self.lock.release()
[ "\n Set the handler class for a subsystem in server mode. If a request\n for this subsystem is made on an open ssh channel later, this handler\n will be constructed and called -- see `.SubsystemHandler` for more\n detailed documentation.\n\n Any extra parameters (including keywor...
Please provide a description of the function:def auth_password(self, username, password, event=None, fallback=True): if (not self.active) or (not self.initial_kex_done): # we should never try to send the password unless we're on a secure # link raise SSHException("No...
[ "\n Authenticate to the server using a password. The username and password\n are sent over an encrypted link.\n\n If an ``event`` is passed in, this method will return immediately, and\n the event will be triggered once authentication succeeds or fails. On\n success, `is_authent...
Please provide a description of the function:def auth_publickey(self, username, key, event=None): if (not self.active) or (not self.initial_kex_done): # we should never try to authenticate unless we're on a secure link raise SSHException("No existing session") if event i...
[ "\n Authenticate to the server using a private key. The key is used to\n sign data from the server, so it must include the private part.\n\n If an ``event`` is passed in, this method will return immediately, and\n the event will be triggered once authentication succeeds or fails. On\n ...
Please provide a description of the function:def auth_interactive(self, username, handler, submethods=""): if (not self.active) or (not self.initial_kex_done): # we should never try to authenticate unless we're on a secure link raise SSHException("No existing session") m...
[ "\n Authenticate to the server interactively. A handler is used to answer\n arbitrary questions from the server. On many servers, this is just a\n dumb wrapper around PAM.\n\n This method will block until the authentication succeeds or fails,\n peroidically calling the handler a...