Skip to content

Commit 946abfe

Browse files
committed
sftp: Fix overwriting existing files while downloading
Thanks @kucharskim for the report and testing! Signed-off-by: Jakub Jelen <[email protected]>
1 parent 09df17e commit 946abfe

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

src/pylibsshext/sftp.pyx

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -89,18 +89,19 @@ cdef class SFTP:
8989

9090
rf = sftp.sftp_open(self._libssh_sftp_session, remote_file_b, O_RDONLY, sftp.S_IRWXU)
9191
if rf is NULL:
92-
raise LibsshSFTPException("Opening remote file [%s] for read failed with error [%s]" % (remote_file, self._get_sftp_error_str()))
93-
94-
while True:
95-
file_data = sftp.sftp_read(rf, <void *>read_buffer, sizeof(char) * 1024)
96-
if file_data == 0:
97-
break
98-
elif file_data < 0:
99-
sftp.sftp_close(rf)
100-
raise LibsshSFTPException("Reading data from remote file [%s] failed with error [%s]"
101-
% (remote_file, self._get_sftp_error_str()))
102-
103-
with open(local_file, 'ab') as f:
92+
raise LibsshSFTPException("Opening remote file [%s] for read failed with error [%s]"
93+
% (remote_file, self._get_sftp_error_str()))
94+
95+
with open(local_file, 'wb') as f:
96+
while True:
97+
file_data = sftp.sftp_read(rf, <void *>read_buffer, sizeof(char) * 1024)
98+
if file_data == 0:
99+
break
100+
elif file_data < 0:
101+
sftp.sftp_close(rf)
102+
raise LibsshSFTPException("Reading data from remote file [%s] failed with error [%s]"
103+
% (remote_file, self._get_sftp_error_str()))
104+
104105
bytes_written = f.write(read_buffer[:file_data])
105106
if bytes_written and file_data != bytes_written:
106107
sftp.sftp_close(rf)

0 commit comments

Comments
 (0)