How secure are temp files created via tempfile.TemporaryFile()?

Steven D'Aprano steve at
Fri Feb 19 01:36:00 CET 2010

On Thu, 18 Feb 2010 15:09:28 -0500, python wrote:

> That's my concern - can other applications really read my temp files
> created with tempfile.TemporaryFile( delete=True )?

>>> import tempfile
>>> x = tempfile.TemporaryFile(delete=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: TemporaryFile() got an unexpected keyword argument 'delete'

The Fine Manual has good information about the security of the various 

    Return a file-like object that can be used as a temporary 
    storage area. ... your code should not rely on a temporary file
    created using this function having or not having a visible name 
    in the file system. ...

    This function operates exactly as TemporaryFile() does, except 
    that the file is guaranteed to have a visible name in the file 
    system ... Whether the name can be used to open the file a 
    second time, while the named temporary file is still open, varies
    across platforms... 

> I don't think so because:
> 1. These files appear to be exclusively locked by my process, eg. no
> other processes can read or write to these temp files except the process
> that created these files.

Exclusive locks are advisory, not mandatory, on some operating systems, 
so you can't rely on it. Recent versions of Windows have an interface to 
allow "backup software" to read files opened in exclusive mode, and I 
believe that the kernel can read *and write* to open files (although I 
welcome correction).

And naturally, if your system is compromised with a root kit, then you 
can't trust *anything*, including file locks. But nobody expects an 
application to take responsibility for working securely in the face of a 
root kit :)

> 2. As soon as my process terminates (voluntarily or involuntarily), the
> temp file gets deleted.
> But I want to make sure.

I think the best practice is platform-dependent:

if = "posix":  # Unix, Linux, OpenBSD, FreeBSD, ... 
    tmpfile = tempfile.TemporaryFile
    delete = None
elif in ["nt", "ce"]:  # Windows NT, XP, 2000, CE, ...
    tmpfile = tempfile.NamedTemporaryFile
    delete = True
    # FIXME What to do for Mac, OS/2, RiscOS, Java?
    tmpfile = tempfile.TemporaryFile
    delete = None
if delete is not None:
    f = tmpfile(*args, delete=delete)
    f = tmpfile(*args)


More information about the Python-list mailing list