【问题标题】:Using Paramiko in Python check if directory can be deleted在 Python 中使用 Paramiko 检查目录是否可以删除
【发布时间】:2020-02-20 09:35:12
【问题描述】:

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

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

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

我该怎么做?

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】:

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


    您将不得不使用另一个 API - 例如。使用SSHClient.exec_command 在shell 中执行一些测试。例如您可以使用test command,例如:

    test -w /parent/directory
    

    【讨论】:

      猜你喜欢
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多