Anoop P Alias
Anoop P Alias

Reputation: 403

create a file from python with owner specified

I am trying to create a file on linux with the owner:group predefined from a python script.

The problem is that the python script runs as root and I cant do the owner setting in 2 steps:

subprocess.call("cp a b", shell=True)
subprocess.call("chown user:group b", shell=True)

as the file creation has to trigger another process via incron that works on the file ownership . If I do it in 2 steps it always trigger a process as root (from the first cp);which I dont want

In short is there a simple way to create a file with the owner and group set at the creation time itself from a python process running as root .

Upvotes: 0

Views: 3961

Answers (2)

cdarke
cdarke

Reputation: 44364

You can change the current process effective uid and gid, but the new user must have read access to the file you are copying from. Is that OK?

import os
import shutil

gid = 20      # Target group id
uid = 501     # Target user id

os.setegid(gid)
os.seteuid(uid)

from_file = '/var/root/rootfile'       # File to copy from (tested on OS X)
to_file = 'rootfile'                   # Filename to copy to
shutil.copyfile(from_file, to_file)

# Switch back to root
os.setegid(0)
os.seteuid(0)

Upvotes: 1

Marcus Müller
Marcus Müller

Reputation: 36352

OK, this is not a python but a UNIX problem:

A file is, by default, always created owned by the user of the creating process.

As root, you can change your effective UID for such operation, and you can change the file ownership afterwards.

cp supports keeping the original owner: cp -a This might already solve your problem.

Setting the UID in your python process is really trivial:

import os
os.setuid(<userid>)

Upvotes: 0

Related Questions