Getting Root Privelges


Recommended Posts

I need root privledges to do some stuff in my python script. I am currently using this technique

current_user = os.geteuid()

if current_user != 0:
   print "you need to be root to run this script"
   sys.exit()

this will atleast politly end the script so i am able to log in as root

Is it a very involved process to have the script prompt me for my root password and switch users?

Link to post
Share on other sites

There's intentionally no (easy) way for a script to acquire root after it's running. Your best bet is to use su or sudo. A sudo'ed reinvocation of the script is one approach.

#!/usr/bin/python

import os
import sys

if os.geteuid() != 0:
   os.execv('/usr/bin/sudo', ['sudo', 'python'] + sys.argv)
   sys.exit(1)

# Rest of the script for euid == 0

with the correct path in the first arg of execv(), or

#!/usr/bin/python

import os
import sys

if os.geteuid() != 0:
   os.system('sudo python ' + ' '.join(sys.argv))
   sys.exit(0)

# Rest of the script for euid == 0

depending on whether you want to keep the unpriv'ed process around.

The idiomatic way to this is to run the script as root and use seteuid() or setuid() to drop privileges when you don't need them.b

By the way, you probably want to be checking os.getuid() as well as geteuid(). It is possible to change the effective UID back to root in many circumstances.

Edited by jcl
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...