Python tempfile.NamedTemporaryFile 的这种用法是否安全(即避免了已弃用的 tempfile.mktemp 的安全问题)?
def mktemp2():
"""Create and close an empty temporary file.
Return the temporary filename"""
tf = tempfile.NamedTemporaryFile(delete=False)
tfilename = tf.name
tf.close()
return tfilename
outfilename = mktemp2()
subprocess.call(['program_name','-o',outfilename])
我需要运行需要输出文件名作为参数之一的外部命令。如果存在而没有警告,它将覆盖输出文件名。我想使用临时文件,因为我只需要阅读它的内容,以后就不需要了。
最佳答案
完全不安全。攻击者有机会在子进程删除和打开文件之间使用他们喜欢的任何权限(或符号链接(symbolic link))创建具有该名称的文件
如果您可以在除/tmp 以外的目录中创建文件,该目录由您的进程拥有并且只能读/写,则您无需担心文件的安全性,因为该目录中的任何内容都受到保护
关于python - python tempfile.NamedTemporaryFile 的这种用法安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3986364/