shanenin Posted July 16, 2005 Report Share Posted July 16, 2005 I need root privledges to do some stuff in my python script. I am currently using this techniquecurrent_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 rootIs it a very involved process to have the script prompt me for my root password and switch users? Quote Link to post Share on other sites
jcl Posted July 17, 2005 Report Share Posted July 17, 2005 (edited) 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/pythonimport osimport sysif os.geteuid() != 0: os.execv('/usr/bin/sudo', ['sudo', 'python'] + sys.argv) sys.exit(1)# Rest of the script for euid == 0with the correct path in the first arg of execv(), or#!/usr/bin/pythonimport osimport sysif os.geteuid() != 0: os.system('sudo python ' + ' '.join(sys.argv)) sys.exit(0)# Rest of the script for euid == 0depending 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.bBy 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 July 17, 2005 by jcl Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.