Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

How to check that my python script is running under Administrator rights (sudo) under BSD-like OS? Need to display user-friendly warning in order it is executed without admin rights.

share|improve this question
add comment

4 Answers 4

up vote 12 down vote accepted

How about this? Check if uid == 0 :

[kbrandt@kbrandt-admin: ~] python -c 'import os; print os.getuid()'

196677

[kbrandt@kbrandt-admin: ~] sudo python -c 'import os; print os.getuid()'

0

share|improve this answer
1  
I actually shortened it :-) . I use likewise open for Linux authentication, which creates a large UID by hashing the Windows SID. –  Kyle Brandt Jun 1 '09 at 13:32
add comment

In Unix-like OSes, the only "Administrator" is the root user with uid=0. (There may be more users with the same uid, and they all will have the same privileges.)

So probably the best way is:

import os
if os.getuid() == 0:
    print("r00tness!")
else:
    print("I cannot run as a mortal. Sorry.")
share|improve this answer
add comment

How about that one:

import os
username=os.system("whoami")
if username is not "root":
    print "You aren't root"
else:
    print "Hello, "+username
share|improve this answer
add comment

Don't be tempted to match a username against the string "root".

Generally you will either have to provide less efficient callouts to obtain the textual representation of the UID or you will be relying on environment variables which may not be so trustworthy.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.