【问题标题】:What is the best way to use os.makedirs() when mode is ignored忽略模式时使用 os.makedirs() 的最佳方法是什么
【发布时间】:2011-06-12 04:04:54
【问题描述】:

在我正在使用的 linux 服务器上,我需要创建具有以下结构的目录:

/dir1/dir2/dir3/YYYY/MM/DD/file.ext

在某些情况下(因为目录取决于日期)我需要一次创建多个目录,例如 .../2011/01/01/,它们都需要权限 0o2755 .

当我在服务器上使用 os.makedirs(dir, mode=0o2755) 时,它会正确设置权限的 0o755 部分,但会忽略 SGID (2) 位。我猜这是因为 os.makedirs 忽略了某些系统上的权限,如文档所述。我读过其他人在使用 umask 和 os.makedirs() 时遇到了问题,但我玩过 umask(它设置为 0002,我尝试过 0000),但它仍然忽略了 SGID 位。

我的解决方案是以下函数:

def special_makedirs(base_dir, target_dir, mode=0o2755):
    base_dir = os.path.abspath(base_dir)
    target_dir = os.path.abspath(target_dir)
    if os.path.commonprefix([base_dir, target_dir]) != base_dir:
        log.error("Target directory %s is not a subdirectory of %s" %(target_dir, base_dir))
        raise ValueError("Target directory %s is not a subdirectory of %s" % (target_dir, base_dir))

    # Create initial directory
    os.makedirs(target_dir, mode=mode)

    # Verify permissions
    temp = target_dir
    while temp != base_dir and stat.S_IMODE(os.stat(temp)) != mode:
        os.chmod(temp, mode)
        temp = os.path.split(temp)[0]

现在我确信这并不满足所有情况,但我将是唯一一个使用此功能来满足我的特定需求的人。

所以...我的问题是:

  1. 当 os.makedirs 文档说它忽略某些系统上的权限时,我是否误解了它?其他人有这个问题吗?

  2. 我的函数似乎是解决此问题的最有效方法吗?

感谢您提供的任何提示。对不起,如果我的情况没有意义。

【问题讨论】:

    标签: python linux permissions


    【解决方案1】:

    来自mkdir(2) 手册页:

    NOTES
            Under  Linux  apart from the permission bits, only the S_ISVTX mode bit
            is honored.  That is, under Linux the created directory  actually  gets
            mode (mode & ~umask & 01777).
    

    所以是的,SGID 被忽略了。事后设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 2013-11-25
      • 1970-01-01
      相关资源
      最近更新 更多