0

How can I check if a script is running with root-privileges?

I am using the following code, but it uses linux commands to get the user id so it would not work on m$ win. Is there an platform independent approach to handle this problem ?

if { [exec id -u] eq 0 } {
    //nice, let us destroy something!
} else {
    //sorry. you are not root
}
NaN
  • 3,501
  • 8
  • 44
  • 77
  • I am sure you're Not a Number –  Aug 08 '13 at 09:04
  • Why do you need admin/root access? I don't know any platform independed thing that requires admin access. Listen on port<1024? *nix it might not work, windows does not care. Writing to a system directory? They are different for each platform. – Johannes Kuhn Aug 08 '13 at 10:06

2 Answers2

5

Windows has no root privileges.
Maybe the SYSTEM account or a member of the Administrators group is what you want.

There is no known platform independent approach that I know of.

I suggest branching for different OS.

  • On Windows: To check if the current process runs as a member of the Administrators group you could do the following thing:

    package require twapi
    set token [twapi::open_process_token]
    set groups [twapi::get_token_groups_and_attrs $token]
    twapi::close_token $token
    if {[dict exists $groups S-1-5-32-544] && {enabled} in [dict get $groups S-1-5-32-544]} {
         puts "I run as administrator"
    } else {
         puts "No admin rights"
    }
    

    This requires twapi, a great package for windows.
    The Administrators' SID is hardcoded, because it is the same on every system, while the name of the Administrators group is not (on my system it is "Administratoren").

    You should check if the group is enabled because starting with Windows Vista there is UAC, which will list the Administrators' group SID (S-1-5-32-544) for members of this group, but with a use_for_deny_only flag. (Only when invoked with the "run as administrator", this group will be enabled.)

  • On Unix/Linux I suggest using TclX.

    here it is simple:

    package require TclX
    if {[id userid]} {
         puts "Not root"
    } else {
         puts "root"
    }
    

    This might even work with OS/X, but I'm not sure.

PS: Don't be evil.

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
0

In perl you can write following to get user name of under which the script is running as follows (independent of OS)

print "Current username is " . (getpwuid($<))[0] . "\n";

I don't know muhc about TCL though - but you can look here how to do getpwnam/getpwuid etc in tcl and here http://wiki.tcl.tk/1649

Community
  • 1
  • 1
Anshul
  • 680
  • 1
  • 5
  • 19
  • thx for the answer, but it wouldn't be much better to use perl. This only works if the uid of the admin user is 0 and I don't know how windows, mac osx handle their uids. Futhermore I would have to install perl -_- – NaN Aug 08 '13 at 09:32