tempfile.mkstemp permissions settings

2.7k Views Asked by At

I am using tempfile.mkstemp to generate a random available filename and write some content with os.fdopen. I then pass the filename to a task via celery.

This task opens the file, processes the content, and finally removes the file. In testing this works fine, however I have realised that this will break in my live environment where the user running the task is not the same as the one which creates the file.

This means that the user cannot open the file because tempfile.mkstemp sets the permissions to 600(-rw-------).

I cannot make both processes run by the same user, so is there some way to modify the file permissions set by tempfile.mkstemp?

I am running Python 3.6 on Ubuntu 14.04.

2

There are 2 best solutions below

1
On BEST ANSWER

Given that you use os.fdopen after you call mkstemp(), you may be better off using tempfile.NamedTemporaryFile(delete=False). It returns a Python file object instead of an fd.

Either way, the returned file will have mode=0600, so you will need to change it. Use os.fchmod(temp_file.fileno(), 0640) or similar (change the mode as per your needs).

5
On

No, apart from manually modyfing permissions using chmod command, there is no way to modify permissions of file created by tempfile.mkstemp. This function by design creates temporary file in the most secure manner possible so the file is readable and writable only by the creating user ID. See mkstemp documentation.

Create your temporary file using tempfile.TemporaryFile or tempfile.NamedTemporaryFile instead.