转自:https://stackoverflow.com/questions/20507055/recursive-remove-directory-using-sftp
注意:SFTP的rmdir只能删除空目录,所以如果目录中存在文件或子目录,需要先删除这些内容再删除该目录。如下所示代码可以参考:
1 import os
2 import paramiko
3 from stat import S_ISDIR
4
5 server =“any.sftpserver”
6 username = “uname”
7 password = “***”
8 path_to_hosts_file = os.path.join("~", “.ssh”, “known_hosts”)
9
10 ssh = paramiko.SSHClient()
11 ssh.load_host_keys(os.path.expanduser(path_to_hosts_file))
12 ssh.connect(server, username=username, password=password)
13
14 def isdir(path):
15 try:
16 return S_ISDIR(sftp.stat(path).st_mode)
17 except IOError:
18 return False
19
20 def rm(path):
21 files = sftp.listdir(path=path)
22
23 for f in files:
24 filepath = os.path.join(path, f)
25 if isdir(filepath):
26 rm(filepath)
27 else:
28 sftp.remove(filepath)
29
30 sftp.rmdir(path)
31
32 if name == “main”:
33 rm("/path/to/some/directory/to/remove")