【问题标题】:Remove particular permission using os.chmod使用 os.chmod 删除特定权限
【发布时间】:2014-11-17 06:26:50
【问题描述】:

我们如何删除所有使用 os.chmod 的特定权限?

简而言之,我们如何使用 os.chmod 编写以下内容

chmod a-x filename

我知道我们可以将权限添加到现有权限并删除。

In [1]: import os, stat
In [5]: os.chmod(file, os.stat(file).st_mode | stat.S_IRGRP)  # Make file group readable.

但我无法弄清楚做所有操作

【问题讨论】:

  • 想想chmod 是如何实现这一目标的;从现有的八进制权限值中删除权限需要采取哪些步骤?
  • 我不是对值进行补码/反转,而是对值进行异或运算。欣赏推理。谢谢。

标签: python unix permissions


【解决方案1】:

如果你想使用 os.chmod() 那么你可以使用下面的代码:

import os
for dir_path, dir_names, files in os.walk('.'):
        for file in files:
            abs_path = os.path.join(dirpath, file)
            os.chmod(abs_path, 0o755) 

【讨论】:

  • 这绝对不是问题的意思。 'chmod a-x filename' 意味着撤销所有用户(用户所有者、组所有者和其他)对给定文件名的可执行权限。
  • 那么您想向用户所有者、组所有者和其他人提供什么权限。所有人都不应该有执行权限,我得到了。读写权限呢?然后我会做出改变。
  • import os for dir_path, dir_names, files in os.walk('.'): for file in files: abs_path = os.path.join(dirpath, file) os.chmod(abs_path, 0o644 ) # 它将提供读写给所有者,只对其他用户读取
  • 只是为了您的好奇心:“读写权限呢?” qn 表示从所有用户中删除文件的可执行权限。理想情况下,这意味着我们应该保留文件具有的其他先前权限。再说一次,你为什么要做 os.walk('.') ? qn 只提到一个文件,而不是整个目录。
【解决方案2】:

酷。所以秘诀是你首先需要获得当前的权限。这有点乱,但它有效。

current = stat.S_IMODE(os.lstat("x").st_mode)

这个想法是 lstat.st_mode 为您提供标志,但您需要将其裁剪到 chmod 接受的范围:

help(stat.S_IMODE)
#>>> Help on built-in function S_IMODE in module _stat:
#>>>
#>>> S_IMODE(...)
#>>>     Return the portion of the file's mode that can be set by os.chmod().
#>>>

然后您可以通过一些位操作删除stat.S_IEXEC 标志,这将为您提供要使用的新数字:

os.chmod("x", current & ~stat.S_IEXEC)

如果您不熟悉位旋转,& 只取两个数字都有的位,~ 反转数字的位。所以x & ~y 获取了x 拥有和y 没有 拥有的那些位。

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 2016-11-21
    • 2017-04-06
    • 2019-07-06
    • 2015-10-15
    • 2021-06-22
    • 2012-11-10
    相关资源
    最近更新 更多