【发布时间】:2012-06-14 06:50:40
【问题描述】:
我希望根据文件是否已经存在来写入文件,仅在文件不存在时写入(实际上,我希望继续尝试文件,直到找到不存在的文件)。
以下代码显示了一种潜在攻击者可以插入符号链接的方式,正如this post 中所建议的那样,在文件测试和正在写入的文件之间。如果代码以足够高的权限运行,这可能会覆盖任意文件。
有没有办法解决这个问题?
import os
import errno
file_to_be_attacked = 'important_file'
with open(file_to_be_attacked, 'w') as f:
f.write('Some important content!\n')
test_file = 'testfile'
try:
with open(test_file) as f: pass
except IOError, e:
# Symlink created here
os.symlink(file_to_be_attacked, test_file)
if e.errno != errno.ENOENT:
raise
else:
with open(test_file, 'w') as f:
f.write('Hello, kthxbye!\n')
【问题讨论】:
-
用 Python 检查原子写入 stackoverflow.com/questions/2333872/…
-
@Mikko 这在这里没有帮助。
-
嗯,好的。我明白这是怎么回事......你只在文件存在时才写?
-
能否将文件写入临时位置,然后执行复制命令且不允许覆盖?
标签: python