[英]Can I set the umask for tempfile.NamedTemporaryFile in python?
在 Python 中(在 2.7 及以下版本中尝试过)它看起来像使用tempfile.NamedTemporaryFile
创建的tempfile.NamedTemporaryFile
似乎不遵守 umask 指令:
import os, tempfile
os.umask(022)
f1 = open ("goodfile", "w")
f2 = tempfile.NamedTemporaryFile(dir='.')
f2.name
Out[33]: '/Users/foo/tmp4zK9Fe'
ls -l
-rw------- 1 foo foo 0 May 10 13:29 /Users/foo/tmp4zK9Fe
-rw-r--r-- 1 foo foo 0 May 10 13:28 /Users/foo/goodfile
知道为什么NamedTemporaryFile
不会选择 umask 吗? 有没有办法在文件创建过程中做到这一点?
我总是可以用 os.chmod() 解决这个问题,但我希望在文件创建过程中做正确的事情。
这是一项安全功能。 NamedTemporaryFile
总是使用模式0600
创建,硬编码在tempfile.py
第 235 行,因为它是您的进程私有的,直到您使用chmod
打开它。 没有构造函数参数来改变这种行为。
如果它可能对某人有所帮助,我想做或多或少相同的事情,这是我使用的代码:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.