Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching users in remote ssh command execution

Tags:

ssh

su

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.

like image 304
Jonathan Ellithorpe Avatar asked Sep 12 '25 00:09

Jonathan Ellithorpe


1 Answers

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.

like image 66
larsks Avatar answered Sep 14 '25 15:09

larsks