Skip to content

Instantly share code, notes, and snippets.

@redperadot
Created April 28, 2014 22:04
Show Gist options
  • Select an option

  • Save redperadot/11385377 to your computer and use it in GitHub Desktop.

Select an option

Save redperadot/11385377 to your computer and use it in GitHub Desktop.

Revisions

  1. Cody Hannafon created this gist Apr 28, 2014.
    24 changes: 24 additions & 0 deletions as_user.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    #!/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