tags:

views:

130

answers:

5

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.

+2  A: 

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.

jdb
If there'll be no other way, I'll try, but now (1) and (2) are mixed a bit.
culebrón
+1  A: 

Would you consider using Linux PAM? You might want to take a look at the Linux-PAM Application Developers' Guide and Python API for PAM

Amit
Interesting thing, thanks, but too complicated in this case, IMO.
culebrón
:) I was wondering, too. But anyways, you may keep in mind for more complex needs. Thanks for the +1.
Amit
+1  A: 

yourscript.py:

run_part_1()
subprocess.call(['sudo', sys.executable, 'part2.py'])
run_part_3()

part2.py:

run_part_2()
nosklo
+1  A: 

You should execute your script as root and do the proper changes to permissions for (3) using os.chmod and os.chown.

It would be possible for you to execute another script with root rights through sudo, but that would also require storing your user's password in the script to pass in to sudo, which is a terrible idea from a security standpoint.

Thus, your issue is about getting the correct permissions on some files/folders. First, pass in or hard code the UID/username of your regular user. Then use os.chown to change the owner, and os.chmod to change the permissions. There are also alternate chown/chmod methods in the os package you should look at: http://docs.python.org/library/os.html

One final note: You don't have to worry about the permissions of symlinks. They have the permissions of what they point to.

Craig Younkins
No need to hard-code what I can get with os.getenv('SUDO_UID').
culebrón
A: 

gnibbler gave a hint at os.chown. The problem was then to know the ID of the user behind sudo. That information is stored in environment variables SUDO_*:

os.chown, (some_path, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

Splitting the code in 3 files could be a solution, but the code is already mixed, so that's not suitable.

culebrón