Other solutions are dependent on the SFTP server operating system. For example, con.execute('rm xxxx')
won't work if the SFTP server is a windows implementation.
For a pysftp only approach to delete non-empty directories, you can use con.walktree
to recursively delete all regular files while building a list of subdirectories to delete after the files.
You can't directly delete the directories from walktree
since it visits the deeper levels last, and you need the opposite.
After the walktree
runs you can iterate (in reverse) over the list of directories and rmdir
each one.
Note that in the code below fcallback=con.remove
so walktree will call remove(remotepath)
for each file recursively.
On the other hand, dcallback=dirs.append
so for each directory will execute dirs.append(directory_remote_path)
, effectively building the list of directories to delete.
import os
import pysftp
sftp_host = os.environ[ 'SFTP_HOST' ]
sftp_username = os.environ[ 'SFTP_USERNAME' ]
sftp_password = os.environ[ 'SFTP_PASSWORD' ]
con = pysftp.Connection(sftp_host, username=sftp_username, password=sftp_password)
dirs = ['/root/backup/data']
con.walktree(dirs[0], fcallback=con.remove, dcallback=dirs.append, ucallback=con.remove, recurse=True)
print(dirs)
for d in reversed(dirs):
print("Delete directory", d)
con.rmdir(d)
con.close()