3

Is it any cross-platform way to check that my python script is executed under admin rights? Unfortunately, os.getuid() is UNIX-only and is not available under windows :(.

grigoryvp
  • 3,795

2 Answers2

3
import ctypes
import os

try:
    is_admin = os.getuid() == 0
except AttributeError:
    is_admin = ctypes.windll.shell32.IsUserAnAdmin()

print is_admin
10se1ucgo
  • 3
  • 4
grigoryvp
  • 3,795
1

"Admin rights" is meaningless. Both Unix and Windows have a long list of different privileges that a particular user may or may not have. You should just try to do what you want to do and use exceptions to deal with lack of privileges. That's that they're there for.

David Pashley
  • 23,637
  • I need to test if script was executed under "su" on unix/macos and under "run as administrator" under vista+. – grigoryvp Jun 22 '09 at 11:04
  • Using exceptions is good, but i need to use third-party applications that have undefined behavior if not run via su/admin, and i do not want to trash a system just to check that script has sufficient rights :) – grigoryvp Jun 22 '09 at 11:05
  • I agree asking for forgiveness rather than permission is right most of the time. But as the OP points out, it's not right all of the time – serverhorror Jun 22 '11 at 00:33