[英]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.