DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Michael has posted 2 posts at DZone. View Full User Profile

Cross-platform detection if running as root/Administrator

02.05.2014
| 2376 views |
  • submit to reddit
require 'rbconfig'

def is_root?
  if RbConfig::CONFIG['host_os'] =~ /mswin|win32|dos|mingw|cygwin/i
    require 'win32/registry'
    
    begin
      Win32::Registry::HKEY_USERS.open('S-1-5-19') {|reg| }
      true
    rescue
      false
    end
  else
    (ENV['USER'] == 'root')
  end
end

Detects if the current running Ruby process is running with Administrative privledges / root.  This works on Linux/Unix, Windows, and JRuby.

is_windows logic came from Puppet.  The registry trick came from Stackoverflow .

Sorry for the bad formatting.  The dzone widget isn't cooperating with me.