[Python-Dev] Remove tempfile.mktemp()

eryk sun eryksun at gmail.com
Thu Mar 21 14:12:54 EDT 2019


On 3/20/19, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Antoine Pitrou wrote:
>
>> How is it more secure than using mktemp()?
>
> It's not, but it solves the problem someone suggested of another
> program not being able to access and/or delete the file.

NamedTemporaryFile(delete=False) is more secure than naive use of
mktemp(). The file is created exclusively (O_EXCL). Another standard
user can't overwrite it. Nor can another standard user delete it if
it's created in the default temp directory (e.g. POSIX "/tmp" has the
sticky bit set). mkstemp() is similar but lacks the convenience and
reliable resource management of a Python file wrapper.

There's still the problem of accidental name collisions with other
processes that can access the file, i.e. processes running as the same
user or, in POSIX, processes running as the super user. I saw a
suggestion in this thread to increase the length of the random
sequence from 8 characters up to 22 characters in order to make this
problem extremely improbable.


More information about the Python-Dev mailing list