
The same stream feeds cat and the shell it's not a good thing. su-ser 'cat whoami'Ĭat will terminate immediately. cat whoami (try it) should print back whatever lines you type (terminate it with Ctrl+ D), then the output of whoami. This way the output is 1 2 3Īnother problem is the remote script passes commands to stdin of the final shell, so you can't easily use its stdin for another purpose. Where the unescaped double-quotes get stripped by the local shell, the single-quotes get stripped by the remote shell finally the escaped double-quotes (that in fact become unescaped as soon as the local shell strips the unescaped ones) tell the shell spawned by su that the string with multiple spaces is a single argument to echo. An uncomplicated local command like echo "1 2 3"īecomes ssh -t "'/path/to/su-ser' 'echo \"1 2 3\"'" This means sometimes you need three levels of quotes to get the right result. The quotes used up by the last shell don't get this far.

The remote shell uses the (now) most outer quotes (if any) to parse it right.

The quotes used up by the shell don't get this far. It uses the most outer quotes (if any) to parse it right. At first your local shell parses the string.Let's analyze what happens to the command. Proper quoting is not a trivial task at this point. On the other hand, if the path is without spaces (and without characters like, *), a totally unquoted ssh … /path/to/su-ser whoami will work as well. The above quoting would work even if /path/to/su-ser contained spaces. From the ssh command in your question body I can tell you probably understand this. You need -t in case sudo asks for the password. The next step is to trigger this remote script from your local computer: ssh -t '"/path/to/su-ser" whoami' To pass a quoted string you need to quote quotes, e.g. Each time printf builds a command from arguments that the script gets, this is passed as a string and then parsed by the final shell, with word splitting, globbing and such. Note these quotes don't propagate to the shell spawned by su. Save it as su-ser, and make it executable.

To make the approach more general, create a script on the server: #!/bin/sh
Sudo su run command password#
( sudo without -S will use the terminal to ask for your password (if needed) despite the redirection). Start by running this on the server: echo whoami | sudo su - serviceAccount There is a way to do something about it, but it's not perfect.

Any solution should use the exact su - serviceAccount command. One or more additional options (like -c) will make the command not qualify. Probably the sudoers file on the remote side specifies the exact command you can run and it's su - serviceAccount.
