kiss-o-matic
kiss-o-matic

Reputation: 1181

Python won't overwrite 777 file

I have a script that is outputting the pid. I change permissions to 777. Every subsequent instance will overwrite this file with the new pid. Despite the 777 permissions, python reports an OS Error that the operation is not permitted unless the user executing the script is the owner of the file. (I can delete/overwrite the file from the shell, of course).

#!/usr/bin/python

import os
import time

f = open("/tmp/test.txt", 'w')
f.write("Hello, file!\n")
os.chmod("/tmp/test.txt", 0777)
f.close()

$ /tmp/myscript.py # fine
$ sudo -u other_user /tmp/myscript.py #not fine -- gives error

Upvotes: 1

Views: 1139

Answers (2)

tdelaney
tdelaney

Reputation: 77337

In Linux, only the user who created the file or root can change its permissions. If the file doesn't exist when you call open, you are the owner of the new file and can change its permissions. When the file already exists, it's just truncated and the existing permissions are still in effect. It would be reasonable to just catch and ignore the error because it only happens after the permissions were setup correctly.

If you have the proper permissions in the parent directory, you can delete the file and create a new one each time. But that doesn't work for /tmp because the sticky bit is set and only owner can delete the file.

Upvotes: 2

lanpa
lanpa

Reputation: 1349

$ /tmp/myscript.py creates a file owned by you.

and $ sudo -u other_user /tmp/myscript.py means other_user is going to change the file permission owned by you.

same as the following situation:

account1$ touch /tmp/test.txt
account1$ chmod 777 /tmp/test.txt
su account2
account2$ chmod 777  /tmp/test.txt 
#chmod: changing permissions of `test.txt': Operation not permitted

Upvotes: 2

Related Questions