Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a way to execute a bash script under the privileges of another user (automatically)? I think "sudo" is the right way, but I don't know how to automate the process.

E.g. I want to run something like this (user "bla" runs a process under "blub"):

sudo <the user under which i want to run the process> <path to script>
share|improve this question
up vote 6 down vote accepted

So did I get that right.

User "bla" wants to run a command as User "blub" ?

Then something like this could work:

sudo -u blub /path/to/command

If you need this to be done without being asked for a password add the follwing line to /etc/sudoers (via visudo command):

bla    ALL=(blub) NOPASSWD: /path/to/command
share|improve this answer

you can work with SUID and SGID bit permissions (note that this may be really dangerous)

give the permissions to execute this file to a group that the user you are executing the script as belong to, and set via SUID anyone who runs this script to run it as the user who owns the script

sudo chmod 4751 /path/to/my/file
sudo chgrp somegroup /path/to/my/file

Then, you just need to execute the script as userB who is member of somegroup and it will be executed with as userA and somegroup

ls -l /path/to/my/file
-rwsr-xr-- userA somegroup /path/to/my/file
share|improve this answer

I wanted to run a script from a cgi. My script generates some directories and files, and I needed them to be owned by nagios user. This is what I did:

edit /etc/sudoers using visudo command
apache   ALL=(nagios) NOPASSWD: /usr/local/nagios/libexec/pangoo_lib/change_state_simulation

From my cgi (apache user), the script is run:

sudo -u nagios /usr/local/nagios/libexec/pangoo_lib/change_state_simulation
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .