15

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.

grigoryvp
  • 3,655
  • 11
  • 39
  • 59

3 Answers3

38

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
Kyle Brandt
  • 83,619
  • 74
  • 305
  • 448
  • 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 01 '09 at 13:32
3

How about that one:

import os
username=os.system("whoami")
if username is not "root":
    print "You aren't root"
else:
    print "Hello, "+username
Severe_admin
  • 338
  • 1
  • 5
2

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.

Dan Carley
  • 25,617
  • 5
  • 53
  • 70