在Python中使用Paramiko检查目录是否可以删除

问题描述 投票:0回答:1

我找到了一种使用 Paramiko 删除远程目录的方法,基于:
如何用Python删除远程SFTP服务器上目录中的所有文件?

但是,如果目录没有有效的权限,则会失败。我已将删除移至异常块。但是,有没有办法检查目录是否具有有效的删除权限?

目前,我注意到在递归目录中,如果其中一个子目录没有写入权限,那么它将无法删除,但我希望删除继续并忽略缺少必要权限的子目录。但是,如果根目录本身没有有效权限,则抛出异常并使用适当的退出代码退出。

我该怎么做?

def rmtree(sftp, remotepath, level=0):

    try:
        for f in sftp.listdir_attr(remotepath):
            rpath = posixpath.join(remotepath, f.filename)
            if stat.S_ISDIR(f.st_mode):
                rmtree(sftp, rpath, level=(level + 1))
            else:
                rpath  = posixpath.join(remotepath, f.filename)
                try:
                    sftp.remove(rpath)
                except Exception as e:
                    print("Error: Failed to remove: {0}".format(rpath))
                    print(e)
    except IOError as io:
        print("Error: Access denied. Do not have permissions to remove: {0} -- {1}".format(remotepath, level))
        print(io)
        if level == 0:
            sys.exit(1)
    except Exception as e:
        print("Error: Failed to delete: {0} -- {1}".format(remotepath, level))
        print(e)
        if level == 0:
            sys.exit(1)
         
    if level <= 2:
        print('removing %s%s' % ('    ' * level, remotepath))
    try:
        sftp.rmdir(remotepath)
    except IOError as io:
        print("Error: Access denied for deleting. Invalid permission")
        print(io)
    
    except Exception as e:
        print("Error: failed while deleting: {0}".format(remotepath))
        print(e)
    
return 
python sftp paramiko stat
1个回答
1
投票

无法“检查” 使用 SFTP 协议进行特定操作的实际权限。 SFTP API 不提供此类功能,也没有足够的信息供您自行决定。 另请参阅
如何使用 JSch 和 SFTP 协议检查读取权限?


您将不得不使用另一个 API – 例如使用

SSHClient.exec_command

 在 shell 中执行一些测试。例如,您可以使用 test
 命令
,例如:

test -w /parent/directory
    
© www.soinside.com 2019 - 2024. All rights reserved.