Reputation: 1256
I use SFTP server for making database backup and all web site with it structure. I use bad script and now I make double duplicates on my SFTP server. I use rmdir folder
but I get error:
Couldn't remove directory: Failure
If I understand right in SFTP I can remove directory just if it empty. And if I use rm folder/*
I don't remove inner folders.
How I can doit another way?
Upvotes: 8
Views: 29804
Reputation: 1256
Implement simple solution in python. I think it somebody help in future
import os
import paramiko
from stat import S_ISDIR
server ="any.sftpserver"
username = "uname"
password = "***"
path_to_hosts_file = os.path.join("~", ".ssh", "known_hosts")
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(path_to_hosts_file))
ssh.connect(server, username=username, password=password)
def isdir(path):
try:
return S_ISDIR(sftp.stat(path).st_mode)
except IOError:
return False
def rm(path):
files = sftp.listdir(path=path)
for f in files:
filepath = os.path.join(path, f)
if isdir(filepath):
rm(filepath)
else:
sftp.remove(filepath)
sftp.rmdir(path)
if __name__ == "__main__":
rm("/path/to/some/directory/to/remove")
Upvotes: 9
Reputation: 191
You can also mount your remote directory with
sshfs [email protected]:/path/to/remote local/path
then just cd local/path
and then you are free to use rm -r folder
Upvotes: 17
Reputation: 99
itdxer's solution is very nice, but it doesn't delete everything: it only deletes a subfolder if it was empty to start with, otherwise it will only delete its contents. It is also possible to make it shorter by combining isdir and rm.
def rm(path):
files = sftp.listdir(path)
for f in files:
filepath = os.path.join(path, f)
try:
sftp.remove(filepath)
except IOError:
rm(filepath)
sftp.rmdir(path)
Upvotes: 9