Over a million developers have joined DZone.

Cross-platform detection if running as root/Administrator

·

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.

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
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}