Running a process as a different user…

I’ve been doing a lot with configuration management lately. At work, I’ve used Chef to set up virtual machines on Amazon Web Services, and I’ve used Ansible at home to create and manage the configuration of my laptop and desktop. Both of these tools let you execute commands as different users than the one that invoked the original script. There are lots of reasons to do this, and it’s a great feature.

At the moment, I’m writing some custom Perl scripts, and I find that I also need to execute some commands as a different user.

So, by inspecting Ansible’s source code, I found that it just uses “sudo”. I figured Chef’s source code was probably a lot larger, so I asked around on IRC, and some very nice people on the #chef channel on freenode showed me the following links:

Rather than using sudo, Chef directly changes the EUID and UID of the process it’s running using the Ruby “Process” module.

A few nights ago, before I learned about how Chef handles it, I was reading about how to do this in Python and found “setuid” and “seteuid” with the Python “os” module.

In Perl, there are lots of ways to do it! If we look at http://perldoc.perl.org/perlvar.html, we’ll see that we can use “$<” and “$>” to change the UID and EUID respectively. That’s not very pretty though… so if you use the “English” module, you can refer to them as “$REAL_USER_ID” and “$EFFECTIVE_USER_ID” or “$UID” and “$EUID”. Or… you can use the “POSIX” module’s “setuid” method which will change both at once.

Cool, eh?

In my case, “sudo” would probably be fine, especially as it should take care of things like changing the group ID, the home directory, etc.


But let’s assume that we want to change the UID and EUID manually in our process. We won’t necessarily know what UID we want to use. We might just have a username. In that case, we can avail ourselves of Perl’s “getpwnam” function.

So let’s take a look at the documentation:

Well, that’s a bit sparse. Here are some alternatives:

So all we need is ‘my $uid = getpwnam(“postgres”);’
Then we can do something like ‘POSIX::setuid($uid);’ to change the UID and EUID of the current process!