Creating a file using python using sudo makes it the root owner

I have a simple part of a python script called myCreate.py running on linux:
fo = open("./testFile.txt", "wb")

when I run python./myCreate.py - the owner of testFile.txt remains my user. when I run sudo python./myCreate.py - the owner of testFile.txt is now root.

testFile.txt has not previously been run for both executions

how can I make the file owner remain a real user, not an effective user ?! Thanks!

+7
python linux file
source share
3 answers

Running a script with sudo means that you are running it as root. So usually your file is owned by root.

What you can do is change the ownership of the file after it is created. To do this, you need to know which user is running sudo. Fortunately, there is an SUDO_UID environment variable that is set when using sudo.

So you can do:

 import os print(os.environ.get('SUDO_UID')) 

Then you need to change the owner of the file :

 os.chown("path/to/file", uid, gid) 

If you put this together:

 import os uid = int(os.environ.get('SUDO_UID')) gid = int(os.environ.get('SUDO_GID')) os.chown("path/to/file", uid, gid) 

Of course, you will want it as a function, because it is more convenient, therefore:

 import os def fix_ownership(path): """Change the owner of the file to SUDO_UID""" uid = os.environ.get('SUDO_UID') gid = os.environ.get('SUDO_GID') if uid is not None: os.chown(path, int(uid), int(gid)) def get_file(path, mode="a+"): """Create a file if it does not exists, fix ownership and return it open""" # first, create the file and close it immediatly open(path, 'a').close() # then fix the ownership fix_ownership(path) # open the file and return it return open(path, mode) 

Using:

 # If you just want to fix the ownership of a file without opening it fix_ownership("myfile.txt") # if you want to create a file with the correct rights myfile = get_file(path) 

EDIT: Updated my answer thanks to @Basilevs, @ Robα΅© and @ 5gon12eder

+6
source share

How about using os.stat to first get the permissions of the contained folder and then apply them to the creation of the file.

it will look something like this (using python2):

 import os path = os.getcwd() statinfo = os.stat(path) fo = open("./testFile.txt", "wb") fo.close() euid = os.geteuid() if (euid == 0) # Check if ran as root, and set appropriate permissioning afterwards to avoid root ownership os.chown('./testFile.txt', statinfo.st_uid, statinfo.st_gid) 

As Elliot noted, if you were to create multiple files at the same time, it would be better structured as a function.

+2
source share

Use os.chown() using os.environ to find the corresponding user id:

 import os fo = open("./testFile.txt", "wb") fo.close() os.chown('./testFile.txt', int(os.environ['SUDO_UID']), int(os.environ['SUDO_GID'])) 
+2
source share

All Articles