Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute os.* methods as root?

Tags:

python

sudo

root

Is it possible to ask for a root pw without storing in in my script memory and to run some of os.* commands as root?

My script

  1. scans some folders and files to check if it can do the job
  2. makes some changes in /etc/...
  3. creates a folder and files that should be owned by the user who ran the script

(1) can be done as a normal user. I can do (2) by sudoing the script, but then the folder and files in (3) will be root's.

The issue is that I use a lot of os.makedirs, os.symlink, etc, which stops me from making it runnable by a normal user.

Tanks 2 all for suggestions

The solution so far is:

# do all in sudo
os.chown(folder, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

thanks to gnibbler for hint.

like image 888
culebrón Avatar asked Nov 18 '25 19:11

culebrón


1 Answers

Maybe you can put (2) in a separate script, say script2.py, and in the main script you call sudo script2.py with a popen ?

This way only (2) will be executed as root.

like image 85
jdb Avatar answered Nov 20 '25 08:11

jdb