如何获取Python中的默认文件权限?

发布于 2024-12-01 02:44:41 字数 213 浏览 1 评论 0原文

我正在编写一个 Python 脚本,其中我将输出写入临时文件,然后在完成并关闭后将该文件移动到其最终目的地。脚本完成后,我希望输出文件具有与通过 open(filename,"w") 正常创建的权限相同的权限。事实上,该文件将具有临时文件模块对临时文件使用的限制性权限集。

有没有办法让我弄清楚如果我就地创建输出文件,它的“默认”文件权限是什么,以便我可以在移动临时文件之前将它们应用到临时文件?

I am writing a Python script in which I write output to a temporary file and then move that file to its final destination once it is finished and closed. When the script finishes, I want the output file to have the same permissions as if it had been created normally through open(filename,"w"). As it is, the file will have the restrictive set of permissions used by the tempfile module for temp files.

Is there a way for me to figure out what the "default" file permissions for the output file would be if I created it in place, so that I can apply them to the temp file before moving it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡淡離愁欲言轉身 2024-12-08 02:44:41

作为记录,我遇到了类似的问题,这是我使用的代码:

import os
from tempfile import NamedTemporaryFile

def UmaskNamedTemporaryFile(*args, **kargs):
    fdesc = NamedTemporaryFile(*args, **kargs)
    # we need to set umask to get its current value. As noted
    # by Florian Brucker (comment), this is a potential security
    # issue, as it affects all the threads. Considering that it is
    # less a problem to create a file with permissions 000 than 666,
    # we use 666 as the umask temporary value.
    umask = os.umask(0o666)
    os.umask(umask)
    os.chmod(fdesc.name, 0o666 & ~umask)
    return fdesc

For the record, I had a similar issue, here is the code I have used:

import os
from tempfile import NamedTemporaryFile

def UmaskNamedTemporaryFile(*args, **kargs):
    fdesc = NamedTemporaryFile(*args, **kargs)
    # we need to set umask to get its current value. As noted
    # by Florian Brucker (comment), this is a potential security
    # issue, as it affects all the threads. Considering that it is
    # less a problem to create a file with permissions 000 than 666,
    # we use 666 as the umask temporary value.
    umask = os.umask(0o666)
    os.umask(umask)
    os.chmod(fdesc.name, 0o666 & ~umask)
    return fdesc
友欢 2024-12-08 02:44:41

os< 中有一个函数 umask /code> 模块。您无法获取当前的 umask 本身,您必须设置它并且该函数返回之前的设置。

umask 是从父进程继承的。它描述了创建文件或目录时要设置的位。

There is a function umask in the os module. You cannot get the current umask per se, you have to set it and the function returns the previous setting.

The umask is inherited from the parent process. It describes, which bits are not to be set when creating a file or directory.

不及他 2024-12-08 02:44:41

这种方式虽然缓慢但安全,并且适用于任何具有“umask”shell 命令的系统:

def current_umask() -> int:
  """Makes a best attempt to determine the current umask value of the calling process in a safe way.

  Unfortunately, os.umask() is not threadsafe and poses a security risk, since there is no way to read
  the current umask without temporarily setting it to a new value, then restoring it, which will affect
  permissions on files created by other threads in this process during the time the umask is changed.

  On recent linux kernels (>= 4.1), the current umask can be read from /proc/self/status.

  On older systems, the safest way is to spawn a shell and execute the 'umask' command. The shell will
  inherit the current process's umask, and will use the unsafe call, but it does so in a separate,
  single-threaded process, which makes it safe.

  Returns:
      int: The current process's umask value
  """
  mask: Optional[int] = None
  try:
    with open('/proc/self/status') as fd:
      for line in fd:
        if line.startswith('Umask:'):
          mask = int(line[6:].strip(), 8)
          break
  except FileNotFoundError:
    pass
  except ValueError:
    pass
  if mask is None:
    import subprocess
    mask = int(subprocess.check_output('umask', shell=True).decode('utf-8').strip(), 8)
  return mask

This way is slow but safe and will work on any system that has a 'umask' shell command:

def current_umask() -> int:
  """Makes a best attempt to determine the current umask value of the calling process in a safe way.

  Unfortunately, os.umask() is not threadsafe and poses a security risk, since there is no way to read
  the current umask without temporarily setting it to a new value, then restoring it, which will affect
  permissions on files created by other threads in this process during the time the umask is changed.

  On recent linux kernels (>= 4.1), the current umask can be read from /proc/self/status.

  On older systems, the safest way is to spawn a shell and execute the 'umask' command. The shell will
  inherit the current process's umask, and will use the unsafe call, but it does so in a separate,
  single-threaded process, which makes it safe.

  Returns:
      int: The current process's umask value
  """
  mask: Optional[int] = None
  try:
    with open('/proc/self/status') as fd:
      for line in fd:
        if line.startswith('Umask:'):
          mask = int(line[6:].strip(), 8)
          break
  except FileNotFoundError:
    pass
  except ValueError:
    pass
  if mask is None:
    import subprocess
    mask = int(subprocess.check_output('umask', shell=True).decode('utf-8').strip(), 8)
  return mask
记忆之渊 2024-12-08 02:44:41
import os

def current_umask() -> int:
    tmp = os.umask(0o022)
    os.umask(tmp)
    return tmp

这个函数在一些python包中实现,例如 安装工具

import os

def current_umask() -> int:
    tmp = os.umask(0o022)
    os.umask(tmp)
    return tmp

This function is implemented in some python packages, e.g. pip and setuptools.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文