[英]Can I set the umask for tempfile.NamedTemporaryFile in python?
In Python (tried this in 2.7 and below) it looks like a file created using tempfile.NamedTemporaryFile
doesn't seem to obey the umask directive:在 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
Any idea why NamedTemporaryFile
won't pick up the umask?知道为什么
NamedTemporaryFile
不会选择 umask 吗? Is there any way to do this during file creation?有没有办法在文件创建过程中做到这一点?
I can always workaround this with os.chmod(), but I was hoping for something that did the right thing during file creation.我总是可以用 os.chmod() 解决这个问题,但我希望在文件创建过程中做正确的事情。
This is a security feature.这是一项安全功能。 The
NamedTemporaryFile
is always created with mode 0600
, hardcoded at tempfile.py
, line 235 , because it is private to your process until you open it up with chmod
. NamedTemporaryFile
总是使用模式0600
创建,硬编码在tempfile.py
第 235 行,因为它是您的进程私有的,直到您使用chmod
打开它。 There is no constructor argument to change this behavior.没有构造函数参数来改变这种行为。
In case it might help someone, I wanted to do more or less the same thing, 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.