Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - How to execute os.* methods as 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...