Linux: Allow user to execute specific command on behalf of any other user

linuxpermissionssusudo

I am trying to find a way to allow user john to execute a command (say echo) on behalf of another user peter without being prompted for password.

I found a thread that I thought would be the answer to my question:

john ALL = (ALL) NOPASSWD: /bin/echo

Unfortunately, this is not quite do what I want. This command executes the echo command as peter but in the context of john. That means the home directory remains that of john.

As the user john, if I run: "sudo -u peter echo ~", the response is: /home/john. I want it to be /home/peter.

The behaviour I was expecting is provided by the su command. As root, if I do: su peter -c "echo ~" , I get /home/peter.

The question this is, how do I get the behavior of su, without being root and without being prompted for password?

Best Answer

You need to specify the -i flag to make sudo read the login scripts & such and set the environment variables as they should be. Without making sudo load the environment, the home environment variable is not updated to reflect the running-as-user.