SFTP

Server-mode SFTP support.

SFTP file object

class paramiko.sftp_file.SFTPFile(sftp, handle, mode='r', bufsize=- 1)

Bases: paramiko.file.BufferedFile

Proxy object for a file on the remote server, in client mode SFTP.

Instances of this class may be used as context managers in the same way that built-in Python file objects are.

check(hash_algorithm, offset=0, length=0, block_size=0)

Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations.

The file is hashed from offset, for length bytes. If length is 0, the remainder of the file is hashed. Thus, if both offset and length are zero, the entire file is hashed.

Normally, block_size will be 0 (the default), and this method will return a byte string representing the requested hash (for example, a string of length 16 for MD5, or 20 for SHA-1). If a non-zero block_size is given, each chunk of the file (from offset to offset + length) of block_size bytes is computed as a separate hash. The hash results are all concatenated and returned as a single string.

For example, check('sha1', 0, 1024, 512) will return a string of length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes of the file, and the last 20 bytes will be the SHA-1 of the next 512 bytes.

Parameters
  • hash_algorithm (str) – the name of the hash algorithm to use (normally "sha1" or "md5")

  • offset – offset into the file to begin hashing (0 means to start from the beginning)

  • length – number of bytes to hash (0 means continue to the end of the file)

  • block_size (int) – number of bytes to hash per result (must not be less than 256; 0 means to compute only one hash of the entire segment)

Returns

str of bytes representing the hash of each block, concatenated together

Raises

IOError – if the server doesn’t support the “check-file” extension, or possibly doesn’t support the hash algorithm requested

Note

Many (most?) servers don’t support this extension yet.

New in version 1.4.

chmod(mode)

Change the mode (permissions) of this file. The permissions are unix-style and identical to those used by Python’s os.chmod function.

Parameters

mode (int) – new permissions

chown(uid, gid)

Change the owner (uid) and group (gid) of this 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.

Parameters
  • uid (int) – new owner’s uid

  • gid (int) – new group id

close()

Close the file.

flush()

Write out any data in the write buffer. This may do nothing if write buffering is not turned on.

gettimeout()

Returns the timeout in seconds (as a float) associated with the socket or ssh Channel used for this file.

See also

Channel.gettimeout

prefetch(file_size=None)

Pre-fetch the remaining contents of this file in anticipation of future read calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file’s contents are incrementally buffered in a background thread.

The prefetched data is stored in a buffer until read via the read method. Once data has been read, it’s removed from the buffer. The data may be read in a random order (using seek); chunks of the buffer that haven’t been read will continue to be buffered.

Parameters

file_size (int) – When this is None (the default), this method calls stat to determine the remote file size. In some situations, doing so can cause exceptions or hangs (see #562); as a workaround, one may call stat explicitly and pass its value in via this parameter.

New in version 1.5.1.

Changed in version 1.16.0: The file_size parameter was added (with no default value).

Changed in version 1.16.1: The file_size parameter was made optional for backwards compatibility.

read(size=None)

Read at most size bytes from the file (less if we hit the end of the file first). If the size argument is negative or omitted, read all the remaining data in the file.

Note

'b' mode flag is ignored (self.FLAG_BINARY in self._flags), because SSH treats all files as binary, since we have no idea what encoding the file is in, or even if the file is text data.

Parameters

size (int) – maximum number of bytes to read

Returns

data read from the file (as bytes), or an empty string if EOF was encountered immediately

readable()

Check if the file can be read from.

Returns

True if the file can be read from. If False, read will raise an exception.

readinto(buff)

Read up to len(buff) bytes into bytearray buff and return the number of bytes read.

Returns

The number of bytes read.

readline(size=None)

Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.

Note

Unlike stdio’s fgets, the returned string contains null characters ('\0') if they occurred in the input.

Parameters

size (int) – maximum length of returned string.

Returns

next line of the file, or an empty string if the end of the file has been reached.

If the file was opened in binary ('b') mode: bytes are returned Else: the encoding of the file is assumed to be UTF-8 and character strings (str) are returned

readlines(sizehint=None)

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.

Parameters

sizehint (int) – desired maximum number of bytes to read.

Returns

list of lines read from the file.

readv(chunks)

Read a set of blocks from the file by (offset, length). This is more efficient than doing a series of seek and read calls, since the prefetch machinery is used to retrieve all the requested blocks at once.

Parameters

chunks – a list of (offset, length) tuples indicating which sections of the file to read

Returns

a list of blocks read, in the same order as in chunks

New in version 1.5.4.

seek(offset, whence=0)

Set the file’s current position.

See file.seek for details.

seekable()

Check if the file supports random access.

Returns

True if the file supports random access. If False, seek() will raise an exception

set_pipelined(pipelined=True)

Turn on/off the pipelining of write operations to this file. When pipelining is on, paramiko won’t wait for the server response after each write operation. Instead, they’re collected as they come in. At the first non-write operation (including close), all remaining server responses are collected. This means that if there was an error with one of your later writes, an exception might be thrown from within close instead of write.

By default, files are not pipelined.

Parameters

pipelined (bool) – True if pipelining should be turned on for this file; False otherwise

New in version 1.5.

setblocking(blocking)

Set blocking or non-blocking mode on the underiying socket or ssh Channel.

Parameters

blocking (int) – 0 to set non-blocking mode; non-0 to set blocking mode.

See also

Channel.setblocking

settimeout(timeout)

Set a timeout on read/write operations on the underlying socket or ssh Channel.

Parameters

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

See also

Channel.settimeout

stat()

Retrieve information about this file from the remote system. This is exactly like SFTPClient.stat, except that it operates on an already-open file.

Returns

an SFTPAttributes object containing attributes about this file.

tell()

Return the file’s current position. This may not be accurate or useful if the underlying file doesn’t support random access, or was opened in append mode.

Returns

file position (number of bytes).

truncate(size)

Change the size of this file. This usually extends or shrinks the size of the file, just like the truncate() method on Python file objects.

Parameters

size – the new size of the file

utime(times)

Set the access and modified times of this file. 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 modified times, respectively. This bizarre API is mimicked from Python for the sake of consistency – I apologize.

Parameters

times (tuple) – None or a tuple of (access time, modified time) in standard internet epoch time (seconds since 01 January 1970 GMT)

writable()

Check if the file can be written to.

Returns

True if the file can be written to. If False, write will raise an exception.

write(data)

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.)

Parameters

datastr/bytes data to write

writelines(sequence)

Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. (The name is intended to match readlines; writelines does not add line separators.)

Parameters

sequence – an iterable sequence of strings.

xreadlines()

Identical to iter(f). This is a deprecated file interface that predates Python iterator support.

Abstraction of an SFTP file handle (for server mode).

An interface to override for SFTP server support.