使用SFTP递归删除目录

2024-06-17 10:57:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用SFTP服务器进行数据库备份和所有具有it结构的网站。我使用了错误的脚本,现在我在SFTP服务器上生成了两个副本。我使用rmdir folder但得到错误:

Couldn't remove directory: Failure

如果我在SFTP中理解正确,我可以删除目录,只要它是空的。如果我使用rm folder/*,我不会删除内部文件夹。

我怎么能换个方式?


Tags: 服务器脚本数据库网站错误副本it备份
3条回答

您还可以使用

sshfs user@yourdomain.com:/path/to/remote local/path

然后只要cd local/path然后就可以使用rm -r folder

itdxer的解决方案非常好,但它并没有删除所有内容:它只删除一个子文件夹,如果它开始时是空的,否则它将只删除其内容。还可以通过综合isdir和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)

用python实现简单的解决方案。我想将来会有人帮忙的

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

相关问题 更多 >