text
stringlengths
81
112k
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 def set_event(self, event): """ Set an event on this buffe...
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`` def feed(self, data): """ Feed new data into this pipe. This method is assumed to be called from a sep...
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 immediately return at least one byte; ``...
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. The optional ``timeout`` argument can be a nonnegative...
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` def empty(self): """ Clear out the buffer and return all data that was in it. :return: any data that was in the bu...
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. ""...
Read an OpenSSH config from the given file object. :param file_obj: a file-like object to read the config file from 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 """ ho...
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 separated by ``Host`` specifications, and t...
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() ...
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 str hostname: the hostname that the config belongs to def _expand_v...
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. 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:: If (for whatever reason) the sto...
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: The result of the krb5 authentication :param str cc_filename: The krb5 client credentials cache filename :retur...
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. :param str username: The username of the authenticating client :param int g...
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``. The default implementation ch...
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 response should be echoed; ``False`` if not (for a passw...
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. We delegate credentials by default. :...
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, the length of the OID and the actual OID encoded with ...
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} def ssh_check_mech(self, desired_mech): """ Check if the given OID is the Kerberos V5 OI...
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 :param str auth_method: The requested SSH authentication mechanism :return: The ...
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 desired_mech: The negotiated GSS-API mechanism ("pseudo negotiated" mechanism, because we ...
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 server, if it's not the initial call. :return: A ``...
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: The negotiated SSPI mechanism ("pseudo negotiated" mechanism, because we ...
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 SSPI for the message we created with ``_ssh_build_mic...
Accept a SSPI context (server mode). :param str hostname: The servers FQDN :param str username: The name of the user who attempts to login :param str recv_token: The SSPI Token received from the server, if it's not the initial call. :return: A ``String`` i...
Verify the MIC token for a SSH2 message. :param str mic_token: The MIC token received from the client :param str session_id: The SSH session ID :param str username: The name of the user who attempts to login :return: None if the MIC check was successful :raises: ``sspi.error`` -...
Checks if credentials are delegated (server mode). :return: ``True`` if credentials are delegated, otherwise ``False`` def credentials_delegated(self): """ Checks if credentials are delegated (server mode). :return: ``True`` if credentials are delegated, otherwise ``False`` ""...
Create an SFTP client channel from an open `.Transport`. Setting the window and packet sizes might affect the transfer speed. The default settings in the `.Transport` class are the same as in OpenSSH and should work adequately for both files transfers and interactive sessions. ...
Generator version of `.listdir_attr`. See the API docs for `.listdir_attr` for overall details. This function adds one more kwarg on top of `.listdir_attr`: ``read_aheads``, an integer controlling how many ``SSH_FXP_READDIR`` requests are made to the server. The default of 50 s...
Rename a file or folder from ``oldpath`` to ``newpath``. .. note:: This method implements 'standard' SFTP ``RENAME`` behavior; those seeking the OpenSSH "POSIX rename" extension behavior should use `posix_rename`. :param str oldpath: existing name of the...
Rename a file or folder from ``oldpath`` to ``newpath``, following posix conventions. :param str oldpath: existing name of the file or folder :param str newpath: new name for the file or folder, will be overwritten if it already exists :raises: ``IOError`` -- if...
Create a folder (directory) named ``path`` with numeric mode ``mode``. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. :param str path: name of the folder to create :param int mode: permissions (posix-st...
Create a symbolic link to the ``source`` path at ``destination``. :param str source: path of the original file :param str dest: path of the newly created symlink def symlink(self, source, dest): """ Create a symbolic link to the ``source`` path at ``destination``. :param str s...
Change the owner (``uid``) and group (``gid``) of a file. As with Python's `os.chown` function, you must pass both arguments, so if you only want to change one, use `stat` first to retrieve the current owner and group. :param str path: path of the file to change the owner and group of ...
Set the access and modified times of the file specified by ``path``. If ``times`` is ``None``, then the file's access and modified times are set to the current time. Otherwise, ``times`` must be a 2-tuple of numbers, of the form ``(atime, mtime)``, which is used to set the access and mo...
Change the size of the file specified by ``path``. This usually extends or shrinks the size of the file, just like the `~file.truncate` method on Python file objects. :param str path: path of the file to modify :param int size: the new size of the file def truncate(self, path, size): ...
Copy the contents of an open file object (``fl``) to the SFTP server as ``remotepath``. Any exception raised by operations will be passed through. The SFTP operations use pipelining for speed. :param fl: opened file or file-like object to copy :param str remotepath: the destina...
Copy a local file (``localpath``) to the SFTP server as ``remotepath``. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. The SFTP operations use pipelining for speed. :param str localpath: the local file to copy :pa...
Copy a remote file (``remotepath``) from the SFTP server and write to an open file or file-like object, ``fl``. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. :param object remotepath: opened file or file-like object to c...
Copy a remote file (``remotepath``) from the SFTP server to the local host as ``localpath``. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. :param str remotepath: the remote file to copy :param str localpath: the destinat...
Raises EOFError or IOError on error status; otherwise does nothing. def _convert_status(self, msg): """ Raises EOFError or IOError on error status; otherwise does nothing. """ code = msg.get_int() text = msg.get_text() if code == SFTP_OK: return elif ...
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. """ path = b(path) if self._cwd is None: ...
Execute all tests (normal and slow) with coverage enabled. def coverage(ctx, opts=""): """ Execute all tests (normal and slow) with coverage enabled. """ return test(ctx, coverage=True, include_slow=True, opts=opts)
Execute all tests and then watch for changes, re-running. def guard(ctx, opts=""): """ Execute all tests and then watch for changes, re-running. """ # 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)
Wraps invocations.packaging.publish to add baked-in docs folder. def release(ctx, sdist=True, wheel=True, sign=True, dry_run=False, index=None): """ Wraps invocations.packaging.publish to add baked-in docs folder. """ # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs...
Normalize/canonicalize ``self.gss_host`` depending on various factors. :param str gss_host: The explicitly requested GSS-oriented hostname to connect to (i.e. what the host's name is in the Kerberos database.) Defaults to ``self.hostname`` (which will be the 'real' target ho...
Negotiate a new SSH2 session as a client. This is the first step after creating a new `.Transport`. A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (successful or not), the given ``Event`` will...
(optional) Load a file of prime moduli for use in doing group-exchange key negotiation in server mode. It's a rather obscure option and can be safely ignored. In server mode, the remote client may request "group-exchange" key negotiation, which asks the server to send a random ...
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.stop_thread() for chan in list(self._channels.values()): chan._u...
Request a new channel to the server, of type ``"session"``. This is just an alias for calling `open_channel` with an argument of ``"session"``. .. note:: Modifying the the window and packet sizes might have adverse effects on the session created. The default values are the same ...
Request a new channel to the server. `Channels <.Channel>` are socket-like objects used for the actual transfer of data across the session. You may only request a channel after negotiating encryption (using `connect` or `start_client`) and authenticating. .. note:: Modifying the the win...
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. The handler parameters are:: handler( channel, ...
Ask the server to cancel a previous port-forwarding request. No more connections to the given address & port will be forwarded across this ssh connection. :param str address: the address to stop forwarding :param int port: the port to stop forwarding def cancel_port_forward(self, addr...
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 int byte_count: the number of random bytes to send...
Return the next channel opened by the client over this transport, in server mode. If no channel is opened before the given timeout, ``None`` is returned. :param int timeout: seconds to wait for a channel, or ``None`` to wait forever :return: a new `.Channel` opened by the c...
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 `start_client`, `get_remote_server_key`, and `Transport.auth_password` or `Transport.auth_publickey`. Use those methods if you want more contr...
Return any exception that happened during the last server request. This can be used to fetch more specific error information after using calls like `start_client`. The exception (if any) is cleared after this call. :return: an exception, or ``None`` if there is no stored ex...
Set the handler class for a subsystem in server mode. If a request for this subsystem is made on an open ssh channel later, this handler will be constructed and called -- see `.SubsystemHandler` for more detailed documentation. Any extra parameters (including keyword arguments) are sav...
Authenticate to the server using a password. The username and password are sent over an encrypted link. If an ``event`` is passed in, this method will return immediately, and the event will be triggered once authentication succeeds or fails. On success, `is_authenticated` will return ...
Authenticate to the server using a private key. The key is used to sign data from the server, so it must include the private part. If an ``event`` is passed in, this method will return immediately, and the event will be triggered once authentication succeeds or fails. On success, `is_...
Authenticate to the server interactively. A handler is used to answer arbitrary questions from the server. On many servers, this is just a dumb wrapper around PAM. This method will block until the authentication succeeds or fails, peroidically calling the handler asynchronously to get...
Autenticate to the server interactively but dumber. Just print the prompt and / or instructions to stdout and send back the response. This is good for situations where partial auth is achieved by key and then the user has to enter a 2fac token. def auth_interactive_dumb(self, username, handler=...
Authenticate to the Server using GSS-API / SSPI. :param str username: The username to authenticate as :param str gss_host: The target host :param bool gss_deleg_creds: Delegate credentials or not :return: list of auth types permissible for the next stage of authenticati...
Set the channel for this transport's logging. The default is ``"paramiko.transport"`` but it can be set to anything you want. (See the `.logging` module for more info.) SSH Channels will log to a sub-channel of the one specified. :param str name: new channel name for logging ...
you are holding the lock def _next_channel(self): """you are holding the lock""" chanid = self._channel_counter while self._channels.get(chanid) is not None: self._channel_counter = (self._channel_counter + 1) & 0xffffff chanid = self._channel_counter self._chann...
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(b(id)) m.add_bytes(self.session_id) # Fallback to SHA1 for...
Checks message type against current auth state. If server mode, and auth has not succeeded, and the message is of a post-auth type (channel open or global request) an appropriate error response Message is crafted and returned to caller for sending. Otherwise (client mode, authed, or pr...
switch on newly negotiated encryption parameters for outbound traffic def _activate_outbound(self): """switch on newly negotiated encryption parameters for outbound traffic""" m = Message() m.add_byte(cMSG_NEWKEYS) self._send_message(m) block_size = self._ciphe...
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()) ...
Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the number of bytes read. :returns: The number of bytes read. def readinto(self, buff): """ Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the number of bytes read. :re...
Read all remaining lines using `readline` and return them as a list. If the optional ``sizehint`` argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. :param int sizehint: ...
Write data to the file. If write buffering is on (``bufsize`` was specified and non-zero), some or all of the data may not actually be written yet. (Use `flush` or `close` to force buffered data to be written out.) :param data: ``str``/``bytes`` data to write def write(self, data): ...
Add a host key entry to the table. Any existing entry for a ``(hostname, keytype)`` pair will be replaced. :param str hostname: the hostname (or IP) to add :param str keytype: key type (``"ssh-rsa"`` or ``"ssh-dss"``) :param .PKey key: the key to add def add(self, hostname, keytype, k...
Read a file of known SSH host keys, in the format used by OpenSSH. This type of file unfortunately doesn't exist on Windows, but on posix, it will usually be stored in ``os.path.expanduser("~/.ssh/known_hosts")``. If this method is called multiple times, the host keys are merged, ...
Find a hostkey entry for a given hostname or IP. If no entry is found, ``None`` is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either ``"ssh-rsa"`` or ``"ssh-dss"``. :param str hostname: the hostname (or IP) to lookup :return: dict of `str` -> ...
Tests whether ``hostname`` string matches given SubDict ``entry``. :returns bool: def _hostname_matches(self, hostname, entry): """ Tests whether ``hostname`` string matches given SubDict ``entry``. :returns bool: """ for h in entry.hostnames: if ( ...
Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the format used by the OpenSSH known_hosts file. Lines are expected to not have leading or trailing whitespace. We don't bother to check for comments or empty l...
Communication with the Pageant process is done through a shared memory-mapped file. def _query_pageant(msg): """ Communication with the Pageant process is done through a shared memory-mapped file. """ hwnd = _get_pageant_window_object() if not hwnd: # Raise a failure to connect exce...
Return the bytes (as a `str`) of this message that haven't already been parsed and returned. def get_remainder(self): """ Return the bytes (as a `str`) of this message that haven't already been parsed and returned. """ position = self.packet.tell() remainder = se...
Returns the `str` bytes of this message that have been parsed and returned. The string passed into a message's constructor can be regenerated by concatenating ``get_so_far`` and `get_remainder`. def get_so_far(self): """ Returns the `str` bytes of this message that have been parsed and ...
Return the next ``n`` bytes of the message (as a `str`), without decomposing into an int, decoded string, etc. Just the raw bytes are returned. Returns a string of ``n`` zero bytes if there weren't ``n`` bytes remaining in the message. def get_bytes(self, n): """ Return the nex...
Add a boolean value to the stream. :param bool b: boolean value to add def add_boolean(self, b): """ Add a boolean value to the stream. :param bool b: boolean value to add """ if b: self.packet.write(one_byte) else: self.packet.write(zer...
Add an integer to the stream. :param int n: integer to add def add_adaptive_int(self, n): """ Add an integer to the stream. :param int n: integer to add """ if n >= Message.big_int: self.packet.write(max_byte) self.add_string(util.deflate_long(n...
Add a 64-bit int to the stream. :param long n: long int to add def add_int64(self, n): """ Add a 64-bit int to the stream. :param long n: long int to add """ self.packet.write(struct.pack(">Q", n)) return self
returns a random # from 0 to N-1 def _roll_random(n): """returns a random # from 0 to N-1""" bits = util.bit_length(n - 1) byte_count = (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 num...
:raises IOError: passed from any file operations that fail. def read_file(self, filename): """ :raises IOError: passed from any file operations that fail. """ self.pack = {} with open(filename, "r") as f: for line in f: line = line.strip() ...
Generate a new private ECDSA key. This factory function can be used to generate a new host key or authentication key. :param progress_func: Not used for this type of key. :returns: A new private key (`.ECDSAKey`) object def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None): ...
Create a key object by reading a private key file. If the private key is encrypted and ``password`` is not ``None``, the given password will be used to decrypt the key (otherwise `.PasswordRequiredException` is thrown). Through the magic of Python, this factory method will exist in all...
Create a key object by reading a private key from a file (or file-like) object. If the private key is encrypted and ``password`` is not ``None``, the given password will be used to decrypt the key (otherwise `.PasswordRequiredException` is thrown). :param file_obj: the file-like object...
Write an SSH2-format private key file in a form that can be read by paramiko 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. :param str tag: ``"RSA"``...
Perform message type-checking & optional certificate loading. This includes fast-forwarding cert ``msg`` objects past the nonce, so that the subsequent fields are the key numbers; thus the caller may expect to treat the message as key material afterwards either way. The obtained key ty...
Supplement the private key contents with data loaded from an OpenSSH public key (``.pub``) or certificate (``-cert.pub``) file, a string containing such a file, or a `.Message` object. The .pub contents adds no real value, since the private key file includes sufficient information to de...
Create a public blob from a ``-cert.pub``-style file on disk. def from_file(cls, filename): """ Create a public blob from a ``-cert.pub``-style file on disk. """ with open(filename) as f: string = f.read() return cls.from_string(string)
Create a public blob from a ``-cert.pub``-style string. def from_string(cls, string): """ Create a public blob from a ``-cert.pub``-style string. """ fields = string.split(None, 2) if len(fields) < 2: msg = "Not enough fields for public blob: {}" raise Va...
Create a public blob from a network `.Message`. Specifically, a cert-bearing pubkey auth packet, because by definition OpenSSH-style certificates 'are' their own network representation." def from_message(cls, message): """ Create a public blob from a network `.Message`. Specif...
wraps a pipe into two pipe-like objects which are "or"d together to affect the real pipe. if either returned pipe is set, the wrapped pipe is set. when both are cleared, the wrapped pipe is cleared. def make_or_pipe(pipe): """ wraps a pipe into two pipe-like objects which are "or"d together to affe...
Return a pair of socket object and string address. May block! def get_connection(self): """ Return a pair of socket object and string address. May block! """ conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: conn.bind(self._agent._get_fi...
Close the current connection and terminate the agent Should be called manually def close(self): """ Close the current connection and terminate the agent Should be called manually """ if hasattr(self, "thread"): self.thread._exit = True self.thread...
Terminate the agent, clean the files, close connections Should be called manually def close(self): """ Terminate the agent, clean the files, close connections Should be called manually """ os.remove(self._file) os.rmdir(self._dir) self.thread._exit = True...
Switch outbound data cipher. def set_outbound_cipher( self, block_engine, block_size, mac_engine, mac_size, mac_key, sdctr=False, ): """ Switch outbound data cipher. """ self.__block_engine_out = block_engine self.__sdc...