Gem utility made to run code as another user
When you have a system administration or automation task and you decide to write a Ruby script that runs as root, but you need to take some actions on behalf of another user (e.g. run an external program or create a file).
gem install as_uid
Or build locally and install:
gem build as_uid.gemspec
gem install ./as_uid-0.0.3.gem
Imagine that on your system the account user has UID 1000. When run as root, this code will create one directory owned by root and one owned by user:
Dir.mkdir("as_root")
Process.as_uid(1000) do
Dir.mkdir("as_user")
%x{whoami}
end
# => "user\n"
Here are the directories:
$ ls -ld as_*
drwxr-xr-x 2 user root 4096 Feb 2 13:06 as_user/
drwxr-xr-x 2 root root 4096 Feb 2 13:06 as_root/
When you’re switching to another user, your permissions are restricted to what that user can do. We can’t remove the as_root directory as a nonroot user (with custom user), because I created it as root:
Process.as_uid(1000) do
Dir.rmdir("as_root")
end
# Errno::EPERM: Operation not permitted - as_root
Dir.rmdir("as_root") # => 0
To run tests use following command:
sudo rake test
Note: You should use sudo because root privileges are expected in test scenarios.
Example run of binary script:
ruby -Ilib ./bin/as_uid 1000 "mkdir 123"
MIT licensed library. See LICENSE for details.
If you have suggestions for improving the as_uid, please open an issue or pull request on GitHub.