在Python中(在2.7及更低版本中尝试过),看起来使用tempfile.NamedTemporaryFile
创建的文件似乎不遵守ummask指令:
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
不拿起面具吗?在文件创建过程中有什么方法可以做到这一点吗?
我总是可以使用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