Becoming root within a Python script

Will Ware wware-nospam at world.std.com
Fri Sep 24 00:14:15 EDT 1999


=?ISO-8859-1?Q?Fran=E7ois_Pinard?= (pinard at iro.umontreal.ca) wrote:
: I would like, within a executing Python started as non-root, ask for the root
: password, and then, continue executing part of the script while being root,
: becoming the previous again after some sub-job is done.

In another post you said you hoped to avoid using 'su'. Can't
help you there, but I did find a pretty simple version that
seems to work well, at least on my Linux box:

---- begin ----
import os, sys
if os.popen('whoami').readline()[:-1] == 'root':
	print 'Hey, look, I am logged in as root!'
else:
	print 'I am the normal user, about to do some root stuff.'
	os.system('su -c "python %s"' % sys.argv[0])
	print 'Normal user again, done doing root stuff.'
---- end ----

Dumb question for those wiser than myself:
The os.popen().readline()[:-1] construction is pretty ugly.
Is there a better way to do it? Aside from the typing and the
esthetics, I'm not altogether certain that the pipe will be
correctly refcounted away and dealloced. I find myself doing
similar things often enough, I'd prefer to hear a better way.
-- 
 - - - - - - - - - - - - - - - - - - - - - - - -
Resistance is futile. Capacitance is efficacious.
Will Ware	email:    wware @ world.std.com




More information about the Python-list mailing list