I'm wondering why executing su
in an ssh
command does not appear to be having the desired effect of switching users before executing the subsequent commands, as illustrated below:
The following command:
bob@server1:~$ sudo ssh -n root@server2 "su bob; env"
Produces the following output:
...
USER=root
PWD=/root
HOME=/root
LOGNAME=root
...
I expected the output to reflect that which user bob would have observed, however it is the environment of the root user. I have found, however, that the following command achieves the desired effect:
bob@server1:~$ sudo ssh -n root@server2 "su bob -c \"env\""
This command produces the following output:
...
USER=bob
PWD=/root
HOME=/users/bob
LOGNAME=bob
...
I would like to understand why the first way (executing "su bob; env"
) does not work.
Consider first what the su
command does: it starts a new shell as the target user. Ignoring ssh for a moment, just become root
on your local system and try running something like this:
su someuser; env
What happens? You will get a shell as someuser
, and when you exit that shell, the env
command executes in root
's environment. If you wanted to run the env
command as someuser
, you would need:
su someuser -c env
This instructs su
to run the env
command as someuser
.
When you run:
sudo ssh -n root@server2 "su bob; env"
The shell spawned by su
exits immediately, because you've disabled stdin (with -n
), and the env
command executes in root
's environment, just like in this example.