API

class sftpretty.CnOpts(config=None, knownhosts='/home/runner/.ssh/known_hosts')

Additional connection options beyond authentication.

Variables:
  • ciphers (tuple) – Default: paramiko.Transport.SecurityOptions.ciphers - Ordered list of preferred ciphers for connection.

  • compress (bool) – Default: paramiko.Transport.use_compression - Enable or disable compression.

  • compression (tuple) – Default: paramiko.Transport.SecurityOptions.compression - Ordered tuple of preferred compression algorithms for connection.

  • paramiko.SSHConfig – SSHConfig object used for parsing and preforming host based lookups on OpenSSH-style config directives.

  • digests (tuple) – Default: paramiko.Transport.SecurityOptions.digests - Ordered tuple of preferred digests/macs for connection.

  • disabled_algorithms (dict) – Default: {} - Mapping type to an iterable of algorithm identifiers, which will be disabled for the lifetime of the transport. Keys should match class builtin attribute.

  • hostkeys (paramiko.hostkeys.HostKeys) – HostKeys object used for host key verifcation.

  • kex (tuple) – Default: paramiko.Transport.SecurityOptions.kex - Ordered tuple of preferred key exchange algorithms for connection.

  • key_types (tuple) – Default: paramiko.Transport.SecurityOptions.key_types - Ordered tuple of preferred public key types for connection.

  • log (bool|str) – Default: False - Log connection details. If set to True, creates a temporary file used to capture logs. If set to an existing filepath, logs will be appended.

  • log_level (str) – Default: info - Set logging level for connection. Choose between debug, error, or info.

Parameters:
  • config (str) – Default: ~/.ssh/config - File path to load config from.

  • knownhosts (str) – Default: ~/.ssh/known_hosts - File path to load hostkeys from.

Returns:

(obj) CnOpts - Connection options object, used for passing extended options to a Connection object.

Raises:
  • ConfigParseError

  • HostKeysException

get_agentkey()

Return the list of keys, if any, available through the local SSH agent. If no agent is running or one cannot be contacted, an empty tuple will be returned.

Returns:

(tuple of AgentKey objects) or (empty tuple)

Raises:

SSHException

get_config(host)

Return config options for a given host-match.

Parameters:

host (str) – Identifier to lookup using OpenSSH’s ssh_config man page ruleset. The first value matched will be returned.

Returns:

(obj) SSHConfigDict - A dictionary wrapper/subclass for per-host configuration structures.

get_hostkey(host)

Return the matching known hostkey to be used for verification or raise an SSHException.

Parameters:

host (str) – The Hostname or IP of the remote machine.

Returns:

(obj) PKey - Public key(s) associated with host or None.

Raises:

SSHException

class sftpretty.Connection(host, cnopts=None, default_path=None, password=None, port=22, private_key=None, private_key_pass=None, timeout=None, username=None)

Connects and logs into the specified hostname. Arguments that are not given are guessed from the environment.

Parameters:
  • host (str) – Required - Hostname or address of the remote machine.

  • cnopts (CnOpts|None) – Default: None - Extended connection options set as a CnOpts object.

  • default_path (str|None) – Default: None - Set the default working directory upon connection.

  • password (str|None) – Default: None - Credential for remote machine.

  • port (int) – Default: 22 - SFTP server port of the remote machine.

  • private_key (str|obj|None) – Default: None - Path to private key file(str) or paramiko.AgentKey object

  • private_key_pass (str|None) – Default: None - Password to use on encrypted private_key.

  • timeout (float|None) – Default: None - Set channel timeout.

  • username (str|None) – Default: None - User for remote machine.

Returns:

(obj) Connection to the requested host.

Raises:
  • ConnectionException

  • CredentialException

  • HostKeysException

  • LoggingException

  • PasswordRequiredException

  • SSHException

property active_ciphers

Get tuple of currently used local and remote ciphers.

Returns:

(tuple of str) currently used ciphers (local_cipher, remote_cipher)

property active_compression

Get tuple of local and remote compression status.

Returns:

(tuple of str) Compression status. (local_compression, remote_compression)

cd(remotepath=None)

Context manager that can change to a optionally specified remote directory and restores the old pwd on exit.

Parameters:

remotepath (str|None) – Default: None - Remote path to maintain as the current working directory.

Returns:

None

Raises:

IOError, if remote path doesn’t exist

chdir(remotepath)

Change the current working directory on the remote

Parameters:

remotepath (str) – Remote path to set as current working directory.

Returns:

None

Raises:

IOError, if path does not exist

chmod(remotepath, mode=700)

Set the permission mode of a remotepath, where mode is an octal.

Parameters:
  • remotepath (str) – Remote path to modify permission.

  • mode (int) – Default: 700 - Octal mode to apply on path.

Returns:

None

Raises:

IOError, if the file doesn’t exist

chown(remotepath, uid=None, gid=None)

Set uid/gid on remotepath, you may specify either or both.

Parameters:
  • remotepath (str) – Remote path to modify ownership.

  • uid (int) – User id to set as owner of remote path.

  • gid (int) – Group id to set on the remote path.

Returns:

None

Raises:

IOError, if user lacks permission or if the file doesn’t exist

close()

Terminate transport connection and clean up the bits.

execute(command, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Execute the given commands on a remote machine. The command is executed without regard to the remote pwd.

Parameters:
  • command (str) – Command to execute.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

(list of str) Results of the command.

Raises:

Any exception raised by command will be passed through.

exists(remotepath)

Test whether a remotepath exists.

Parameters:

remotepath (str) – Remote location to verify existance of.

Returns:

(bool) True, if remotepath exists, else False.

get(remotefile, localpath=None, callback=None, max_concurrent_prefetch_requests=None, prefetch=True, preserve_mtime=False, resume=False, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Copies a file between the remote host and the local host.

Parameters:
  • remotefile (str) – The remote path and filename to retrieve.

  • localpath (str) – The local path to save download. If None, file is copied to local current working directory.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • preserve_mtime (bool) – Default: False - Sync the modification time(st_mtime) on the local file to match the time on the remote. (st_atime can differ because stat’ing the localfile can/does update it’s st_atime).

  • max_concurrent_prefetch_requests (int) – Default: None - The maximum number of concurrent read requests to prefetch.

  • prefetch (bool) – Default: True - Controls whether prefetching is performed.

  • resume (bool) – Default: False - Continue a previous transfer based on destination path matching.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

None

Raises:

IOError

get_d(remotedir, localdir, callback=None, max_concurrent_prefetch_requests=None, pattern=None, prefetch=True, preserve_mtime=False, resume=False, workers=None, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Get the contents of remotedir and write to locadir. Non-recursive.

Parameters:
  • remotedir (str) – The remote directory to copy locally.

  • localdir (str) – The local path to save download.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • max_concurrent_prefetch_requests (int) – Default: None - The maximum number of concurrent read requests to prefetch.

  • pattern (str) – Default: None - Filter applied to filenames to transfer only subset of files in a directory.

  • prefetch (bool) – Default: True - Controls whether prefetching is performed.

  • preserve_mtime (bool) – Default: False - Sync the modification time(st_mtime) on the local file to match the time on the remote. (st_atime can differ because stat’ing the localfile can/does update it’s st_atime)

  • resume (bool) – Default: False - Continue a previous transfer based on destination path matching.

  • workers (int) – Default: None - If None, defaults to number of processors plus 4. Set to less than or equal to allowed concurrent connections on server.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

None

Raises:

Any exception raised by operations will be passed through.

get_r(remotedir, localdir, callback=None, max_concurrent_prefetch_requests=None, pattern=None, prefetch=True, preserve_mtime=False, resume=False, workers=None, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Recursively copy remotedir structure to localdir

Parameters:
  • remotedir (str) – The remote directory to recursively copy.

  • localdir (str) – The local path to save recursive download.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • max_concurrent_prefetch_requests (int) – Default: None - The maximum number of concurrent read requests to prefetch.

  • pattern (str) – Default: None - Filter applied to all filenames transfering only the subset of files that match.

  • prefetch (bool) – Default: True - Controls whether prefetching is performed.

  • preserve_mtime (bool) – Default: False - Sync the modification time(st_mtime) on the local file to match the time on the remote. (st_atime can differ because stat’ing the localfile can/does update it’s st_atime)

  • resume (bool) – Default: False - Continue a previous transfer based on destination path matching.

  • workers (int) – Default: None - If None, defaults to number of processors plus 4. Set to less than or equal to allowed concurrent connections on server.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

None

Raises:

Any exception raised by operations will be passed through.

getcwd()

Return the current working directory on the remote.

Returns:

(str) Remote current working directory. None, if not set.

getfo(remotefile, flo, callback=None, max_concurrent_prefetch_requests=None, prefetch=True, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Copy a remote file (remotepath) to a file-like object, flo.

Parameters:
  • remotefile (str) – The remote path and filename to retrieve.

  • flo – Open file like object ready to write.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • max_concurrent_prefetch_requests (int) – Default: None - The maximum number of concurrent read requests to prefetch.

  • prefetch (bool) – Default: True - Controls whether prefetching is performed.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

(int) The number of bytes written to the opened file object

Raises:

Any exception raised by operations will be passed through.

isdir(remotepath)

Determine if remotepath is a directory.

Parameters:

remotepath (str) – Remote location to test.

Returns:

(bool)

isfile(remotepath)

Determine if remotepath is a file.

Parameters:

remotepath (str) – Remote location to test.

Returns:

(bool)

lexists(remotepath)

Determine whether remotepath exists.

Parameters:

remotepath (str) – Remote location to test.

Returns:

(bool), True, if lexists, else False

listdir(remotepath='.')

Return a sorted list of a directory’s contents.

Parameters:

remotepath (str) – Remote location to search.

Returns:

(list of str) Sorted directory content.

listdir_attr(remotepath='.')

Return a non-sorted list of SFTPAttribute objects for the remote directory contents. Will not include the special entries ‘.’ and ‘..’.

The returned SFTPAttributes objects will each have an additional field: longname, which may contain a formatted string of the file’s attributes, in unix format. The content of this string will depend on the SFTP server.

Parameters:

remotepath (str) – Remote location to search.

Returns:

(list of SFTPAttributes) Sorted directory content as objects.

property logfile

Return logging setting.

Returns:

(str) logfile or (bool) False

lstat(remotepath)

Return information about remote location without following symbolic links. Otherwise, the same as .stat().

Parameters:

remotepath (str) – Remote location to stat.

Returns:

(obj) SFTPAttributes object

mkdir(remotedir, mode=700)

Create a directory and set permission mode. On some systems, mode is ignored. Where used, the current umask value is first masked out.

Parameters:
  • remotedir (str) – Remote location to create.

  • mode (int) – Default: 700 - Octal mode to apply on path.

Returns:

None

mkdir_p(remotedir, mode=700)

Create a directory and any missing parent locations as needed. Set permission mode, if created. Silently complete if remotedir already exists.

Parameters:
  • remotedir (str) – Remote location to create.

  • mode (int) – Default: 700 - Octal mode to apply on created paths.

Returns:

None

Raises:

OSError

normalize(remotepath)

Return the fully expanded path of a given location. This can be used to resolve symlinks or determine what the server believes to be the pwd, by passing ‘.’ as remotepath.

Parameters:

remotepath (str) – Remote location to be normalized.

Returns:

(str) Normalized path.

Raises:

IOError, if remotepath can’t be resolved

open(remotefile, bufsize=-1, mode='r')

Open a file on the remote server.

Parameters:
  • remotefile (str) – Path of remote file to open.

  • mode (str) – Default: read-only - File access mode.

  • bufsize (int) – Default: -1 - Buffering in bytes.

Returns:

(obj) SFTPFile, a file-like object handler.

Raises:

IOError, if the file could not be opened.

put(localfile, remotepath=None, callback=None, confirm=True, preserve_mtime=False, resume=False, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Copies a file between the local host and the remote host.

Parameters:
  • localfile (str) – The local path and filename to copy remotely.

  • remotepath (str) – Remote location to save file, else the remote pwd and local filename is used.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • confirm (bool) – Default: True - Whether to do a stat() on the file afterwards to the file size.

  • preserve_mtime (bool) – Default: False - Make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat’ing the localfile can/does update it’s st_atime)

  • resume (bool) – Default: False - Continue a previous transfer based on destination path matching.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

(obj) SFTPAttributes containing details about the given file.

Raises:
  • IOError – if remotepath doesn’t exist

  • OSError – if localfile doesn’t exist

put_d(localdir, remotedir, callback=None, confirm=True, preserve_mtime=False, resume=False, workers=None, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Copies a local directory’s contents to a remotepath

Parameters:
  • localdir (str) – The local directory to copy remotely.

  • remotedir (str) – The remote location to save directory.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • confirm (bool) – Default: True - Whether to do a stat() on the file afterwards to confirm the file size.

  • preserve_mtime (bool) – Default: False - Make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat’ing the localfile can/does update it’s st_atime)

  • resume (bool) – Default: False - Continue a previous transfer based on destination path matching.

  • workers (int) – Default: None - If None, defaults to number of processors plus 4. Set to less than or equal to allowed concurrent connections on server.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

None

Raises:
  • IOError – if remotedir doesn’t exist

  • OSError – if localdir doesn’t exist

put_r(localdir, remotedir, callback=None, confirm=True, preserve_mtime=False, resume=False, workers=None, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Recursively copies a local directory’s contents to a remotepath

Parameters:
  • localdir (str) – The local directory to copy remotely.

  • remotedir (str) – The remote location to save directory.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • confirm (bool) – Default: True - Whether to do a stat() on the file afterwards to confirm the file size.

  • preserve_mtime (bool) – Default: False - Make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat’ing the localfile can/does update it’s st_atime)

  • resume (bool) – Default: False - Continue a previous transfer based on destination path matching.

  • workers (int) – Default: None - If None, defaults to number of processors plus 4. Set to less than or equal to allowed concurrent connections on server.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Default: None - Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

None

Raises:
  • IOError – if remotedir doesn’t exist

  • OSError – if localdir doesn’t exist

putfo(flo, remotepath=None, file_size=None, callback=None, confirm=True, exceptions=None, tries=None, backoff=2, delay=1, logger=<Logger sftpretty (WARNING)>, silent=False)

Copies the contents of a file like object to remotepath.

Parameters:
  • flo – File-like object that supports .read()

  • remotepath (str) – The remote location to save contents of object.

  • file_size (int) – The size of flo, if not given, calculated preventing division by zero in default callback function.

  • callback (callable) – Optional callback function (form: func( int, int)) that accepts the bytes transferred so far and the total bytes to be transferred.

  • confirm (bool) – Default: True - Whether to do a stat() on the file afterwards to confirm the file size.

  • exceptions (Exception) – Exception(s) to check. May be a tuple of exceptions to check. IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM))

  • tries (int) – Times to try (not retry) before giving up.

  • backoff (int) – Default: 2 - Backoff multiplier. Default will double the delay each retry.

  • delay (int) – Default: 1 - Initial delay between retries in seconds.

  • logger (logging.Logger) – Default: Logger(__name__) - Logger to use.

  • silent (bool) – Default: False - If set then no logging will be attempted.

Returns:

(obj) SFTPAttributes containing details about the given file.

Raises:

TypeError, if remotepath not specified, any underlying error

property pwd

Return the current working directory.

Returns:

(str) Current working directory.

Return the target of a symlink as an absolute path.

Parameters:

remotelink (str) – Remote location of the symlink.

Returns:

(str) Absolute path to target.

property remote_server_key

Return the remote server’s key

remotetree(container, remotedir, localdir, recurse=True)

Recursively map remote directory tree to a dictionary container.

Parameters:
  • container (dict) – Hash table to save remote directory tree. {remotedir: [(remotedir/subdir, localdir/remotedir/subdir)]}

  • remotedir (str) – Remote location to descend, use ‘.’ to start at pwd.

  • localdir (str) – Location used as root of appended remote paths.

  • recurse (bool) – Default: True - To recurse or not to recurse that is the question.

Returns:

None

Raises:

Exception

remove(remotefile)

Delete the remote file. May include a path, if no path, then pwd is used. This method only works on files.

Parameters:

remotefile (str) – Remote file to delete.

Returns:

None

Raises:

IOError

rename(remotepath, newpath)

Rename a path on the remote host.

Parameters:
  • remotepath (str) – Remote path to rename.

  • newpath (str) – New name for remote path.

Returns:

None

Raises:

IOError

rmdir(remotedir)

Delete remote directory.

Parameters:

remotedir (str) – Remote directory to delete.

Returns:

None

property security_options

Return the transport security options.

Returns:

(obj) Security preferences for the underlying transport. These are tuples of acceptable .ciphers, .digests, .key_types and key exchange algorithms .kex, listed in order of preference.

property sftp_client

Provide access to the underlying SFTPClient object. Client is not handled by context manager. Connection is closed with underlying transport if not done explicitly.

Params:

None

Returns:

(obj) Active SFTPClient object.

stat(remotepath)

Return information about remote location.

Parameters:

remotepath (str) – Remote location to stat.

Returns:

(obj) SFTPAttributes

Create a symlink for a remote file on the server

Parameters:
  • remote_src (str) – path of original file

  • remote_dest (str) – path of the created symlink

Returns:

None

Raises:

any underlying error, IOError if remote_dest already exists

property timeout

Get or set the underlying socket timeout for pending IO operations.

Returns:

(float|None) Seconds to wait for pending read/write operation before raising socket.timeout, or None for no timeout

truncate(remotepath, size)

Change the size of the file specified by path. Used to modify the size of the file, just like the truncate method on Python file objects. The new file size is confirmed and returned.

Parameters:
  • remotepath (str) – remote file path to modify

  • size (int|long) – the new file size

Returns:

(int) new size of file

Raises:

IOError, if file does not exist

SecurityOptions

A simple object returned with available security preferences.

See Security Options for details.

SFTPAttributes

Representation of the attributes of a file or proxied file.

See SFTPAttributes for details.

SFTPFile

Proxy object for a file on the remote server.

See SFTPFile for details.