Run Ruby block as a specific OS user?

Is it possible to execute a block of Ruby code as another OS user?

What I ideally want is something like this:

user("christoffer") do
  # do something
end

Possible?

+3
source share
1 answer

This code can do what you want. Error handling is up to you .; -)

require 'etc'

def as_user(user, &block)
    u = Etc.getpwnam(user)
    Process.fork do
        Process.uid = u.uid
        block.call(user)
    end
end

puts("caller PID = #{Process.pid}")
puts("caller UID = #{Process.uid}")
as_user "bmc" do |user|
    puts("In block as #{user} (uid=#{Process.uid}), pid is #{Process.pid}")
end

Note, however, that you will need to run Ruby as rootor as setuid-to- root, which has some serious security implications.

+7
source

Source: https://habr.com/ru/post/1782480/


All Articles