You're executing the command
sudo su - USER2; whoami; pwd on the remote host. Let's decompose that:
- Commands separated by a semicolon are executed in sequence. Thus the command
sudo su - USER2 is executed first; then, when it finishes,
whoami is executed, and finally
pwd is executed.
- The command
sudo su - USER2 starts a login shell as user USER2. This shell reads commands from standard input until it's told to exit (e.g. with the
exit builtin) or until it detects an end of file on standard input. Since standard input is connected to the terminal, it waits for you to type commands.
If you want to execute commands as USER2, you need to pass them as arguments to
su isn't useful here, sudo already knows how to do this. You don't need the
-t option to SSH unless you want to interact with the remote commands (this includes the case when you need to type a password for sudo).
ssh -t "$remotehost" 'sudo -i -u USER2 sh -c "whoami; pwd"'
If your sudo configuration only allows you to run programs as root, not as an arbitrary user (which doesn't change anything security-wise), then you'll need to stick to
sudo su. In that case, pass the
-c option to
su to run the specified shell command.
ssh -t "$remotehost" 'sudo su -c "whoami; pwd" USER2'
If you need to read the user's
.profile, do so explicitly.
ssh -t "$remotehost" 'sudo su -c ". ~/.profile; whoami; pwd" USER2'
Alternatively, you can pass the commands as standard input to an interactive shell. The plumbing is a little delicate since ssh's standard input must remain the terminal. An advantage of this approach with a here document is that quoting in the shell command remains relatively simple: escape
'\'' for the remote shell, no escaping is needed for the remote shell.
ssh -t "$remotehost" 'sudo su - USER2 <<\EOF