Skip to main content
 首页 » 编程设计

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

2024年11月01日11shihaiming

我找到了一种使用 Paramiko 删除远程目录的方法,基于:
How to delete all files in directory on remote SFTP server in Python?

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

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

我该怎么做?

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  

请您参考如下方法:

不可能“检查”使用 SFTP 协议(protocol)的特定操作的实际权限。 SFTP API 不提供此类功能,也没有足够的信息供您自行决定。
另见 How to check for read permission using JSch with SFTP protocol?


您将不得不使用其他 API——例如使用 SSHClient.exec_command 在 shell 中执行一些测试.例如,您可以使用 test command ,例如:

test -w /parent/directory