I am trying to navigate from one serverUSER1 to another using ssh as a user USER2.ssh -t $hostname sudo su - USER2; whoami; pwdPost executing the above, I am able to successfully navigate to the server as USER2, but the trailing commands i.e whoami and pwd are not getting executed.However, while exiting the ssh session USER1 is rendered in the output followed by the present working directory.I do not want to make any changes in the ssh known hosts file.
How to run multiple sudo commands over already opened ssh connection
linux;bash;ssh;sudo
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 sudo. Running 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 ' as '\'' for the remote shell, no escaping is needed for the remote shell.ssh -t $remotehost 'sudo su - USER2 <<\EOFwhoamipwdEOF'