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

Snippets has posted 5883 posts at DZone. View Full User Profile

Runas - Run A Program Under A Specific User / Group (poor Man's Suexec)

04.10.2008
| 6710 views |
  • submit to reddit
        
#!/usr/bin/env ruby

# runas - Run another program under the privileges of a specified user and group.
# This is necessary because sudo demands a password, as we need it to be hands off.
# A poor man's suexec basically.

require 'etc'

user, group, cmd = ARGV

begin
  uid = Etc.getpwnam(user).uid
  gid = Etc.getgrnam(group).gid

  unless Process.euid == uid && Process.egid == gid
    Process.initgroups(user, gid)
    Process::GID.change_privilege(gid)
    Process::UID.change_privilege(uid)
  end

  exec cmd
rescue
  puts "Could not run as #{user}:#{group}"
  exit 1
end

Usage example: ./runas username groupname "sleep 10"