Skip to content

Instantly share code, notes, and snippets.

@redperadot
Created April 28, 2014 22:04
Show Gist options
  • Save redperadot/11385377 to your computer and use it in GitHub Desktop.
Save redperadot/11385377 to your computer and use it in GitHub Desktop.
Run a block of code as another user in Ruby. You could use it to unsudo a sudoed script.
#!/usr/bin/env ruby
require 'etc'
def as_user(user = Etc.getlogin, &block)
u = (user.is_a? Integer) ? Etc.getpwuid(user) : Etc.getpwnam(user)
puts "Running child process as the user #{user}(#{u.uid})."
pid = Process.fork do
Process.uid = u.uid
block.call(user)
end
print "Waiting for the process #{pid} to finish...\r"
Process.wait(pid)
puts "The process #{pid} has finished. "
end
# Run block as the sudoer (unsudo).
as_user do
system("sleep 3")
end
# Run block as another user.
as_user "OtherUser" do
system("sleep 3")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment