Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 14 down vote accepted

How about this? Check if uid == 0:

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

[kbrandt@kbrandt-admin: ~] sudo python -c 'import os; print os.getuid()'
share|improve this answer
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

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("I cannot run as a mortal. Sorry.")
share|improve this answer

How about that one:

import os
if username is not "root":
    print "You aren't root"
    print "Hello, "+username
share|improve this answer

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

Your Answer


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.