2

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?

2 Answers 2

1

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.

2
  • Thanks for answering. Is this what you have in mind? "sudo -i -u peter echo ~". Adding -i now prompts john for password.
    – Klaus
    Feb 8, 2016 at 16:10
  • hmmm... it shouldn't ask for a password if sudo does not require it... let me do some digging.
    – TheCompWiz
    Feb 8, 2016 at 16:17
0

"sudo -u peter echo ~" will interpret the value of ~ before executing the command sudo. Try

sudo -s -H -u peter echo \$HOME

or

sudo -i -u peter echo \$HOME

Also, to view all environment variables set by sudo try:

sudo -i -u peter export
# actually, use /usr/bin/env instead of export

UPDATE

When using -i or -s you are implying that the SUDO_COMMAND to run is the shell environment of the specified user. So allowing for only /bin/echo is not sufficient, one would have to allow for all of /bin/bash to be available.

It seems that -H is enough to set HOME environment variable, but you cannot echo it with $HOME because that is a feature of a shell. Other programs may be able to read the value of HOME via getenv() or similar methods.

sudo -H -u peter  /usr/bin/env | grep SUDO_COMMAND
SUDO_COMMAND=/usr/bin/env

sudo -i -u peter /usr/bin/env | grep SUDO_COMMAND
SUDO_COMMAND=/bin/bash -c /usr/bin/env
4
  • 1
    As soon as you add another option, sudo prompts for password.
    – Klaus
    Feb 8, 2016 at 17:21
  • Because you are only allowing "/bin/echo" but -i wants the command to be /bin/bash (or whatever is set in /etc/passwd as the shell)
    – chugadie
    Feb 8, 2016 at 17:26
  • Sorry. I am not quite sure i understand what else i should allow.
    – Klaus
    Feb 8, 2016 at 18:06
  • You don't need to change anything. Your original setup is correct. Your assumptions about testing with ~ are incorrect.
    – chugadie
    Feb 8, 2016 at 18:26

You must log in to answer this question.

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