Created
April 28, 2014 22:04
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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