Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have a system that I can only log in to under my username (myuser), but I need to run commands as other user (scriptuser). So far, I have come up with the following to run the commands I need:

ssh -tq myuser@hostname "sudo -u scriptuser bash -c \"ls -al\""

If however, when I try to run a more complex command, such as [[ -d "/tmp/Some directory" ]] && rm -rf "/tmp/Some directory" I quickly get into trouble with quoting. I'm not sure how I could pass this example complex command to bash -c, when \" already delimites the boundaries of the command I'm passing (and so I don't know how to quote /tmp/Some directory, which includes a spaces.

Is there a general solution allowing me to pass any command no matter how complex/crazy the quoting is, or is this some sort of limitation I have reached? Are there other possible and perhaps more readable solutions?

share|improve this question
Copy a script to $remote then execute it. –  Iain Sep 2 '14 at 9:24
That would work, but I find a solution which leaves no script files behind (in case something fails etc.) would be a bit cleaner. –  VoY Sep 2 '14 at 9:29
have the script rm itself at end of each run –  thanasisk Sep 2 '14 at 9:36
Consider to use fabric fabfile.org. Can make you life much easier if you have to sudo remotely a lot. –  Nils Toedtmann Sep 2 '14 at 12:10
If you have Ansible installed this command shows the documentation for your use case: ansible-doc script –  datasmid Sep 5 '14 at 5:03

8 Answers 8

up vote 85 down vote accepted

A trick I use sometimes is to use base64 to encode the commands, and pipe it to bash on the other site:

MYCOMMAND=`base64 -w0 script.sh`
ssh user@remotehost "echo $MYCOMMAND | base64 -d | sudo bash"

This will encode the script, with any commas, backslashes, quotes and variables inside a safe string, and send it to the other server. (-w0 is required to disable line wrapping, which happens at column 76 by default). On the other side, base64 -d will decode the script and feed it to bash to be executed.

I never got any problem with it, no matter how complex the script was. Solves the problem with escaping, because you don't need to escape anything. It does not creates a file on the remote host, and you can run vastly complicated scripts with ease.

share|improve this answer
You can base64 script.sh to avoid a UUOC –  l0b0 Sep 2 '14 at 19:15
Thanks! I used to point it to other users and ended up doing the same. Fixed. –  ThoriumBR Sep 2 '14 at 19:45
Or even: ssh user@remotehost "echo `base64 -w0 script.sh` | base64 -d | sudo bash" –  Niklas B. Sep 3 '14 at 23:49
It's worth noting that in most cases you can substitute lzop or gzip for base64 for faster transfer times. However, there may be edge cases. YMMV. –  CodeGnome Sep 4 '14 at 12:29
Good note, but if it's a script, I don't expect any transfer to be more than a few kb. –  ThoriumBR Sep 4 '14 at 12:33

See the -tt option? Read the ssh(1) manual.

ssh -tt root@host << EOF
sudo some # sudo shouldn't ask for a password, otherwise, this fails. 
but be careful with \$variables
and \$(other) \`stuff\`
exit # <- Important. 

One thing I often do is use vim and use the :!cat % | ssh -tt somemachine trick.

share|improve this answer
Of course :!cat % | (command) can be done as :w !(command) or :!(command) < %. –  Scott Sep 4 '14 at 17:51
Yes. My line is a cat abuse –  moebius_eye Sep 5 '14 at 9:13

I think the easiest solution lies in a modification of @thanasisk's comment.

Create a script, scp it to the machine, then run it.

Have the script rm itself at the start. The shell has opened the file, so it's been loaded, and can then be removed without problems.

By doing things in this order (rm first, other stuff second) it'll even be removed when it fails at some point.

share|improve this answer

Are you aware that you can use sudo to give you a shell where you can run commands as the chosen user?

-i, --login

Run the shell specified by the target user's password database entry as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution via the shell's -c option. If no command is specified, an interactive shell is executed. sudo attempts to change to that user's home directory before running the shell. The com‐ mand is run with an environment similar to the one a user would receive at log in. The Command Environment section in the sudoers(5) manual docu‐ ments how the -i option affects the environment in which a command is run when the sudoers policy is in use.

share|improve this answer
this seems like the obvious solution to me. > sudo -i -u brian –  sean9999 Sep 7 '14 at 2:26

You can use the %q format specifier with printf to take care of the variable escaping for you:

cmd="ls -al"
printf -v cmd_str '%q' "$cmd"
ssh user@host "bash -c $cmd_str"

printf -v writes the output to a variable (in this case, $cmd_str). I think that this is the simplest way to do it. There's no need to transfer any files or encode the command string (as much as I like the trick).

Here's a more complex example showing that it works for things like square brackets and ampersands too:

$ ssh user@host "ls -l test"
-rw-r--r-- 1 tom users 0 Sep  4 21:18 test
$ cmd="[[ -f test ]] && echo 'this really works'"
$ printf -v cmd_str '%q' "$cmd"
$ ssh user@host "bash -c $cmd_str"
this really works

I haven't tested it with sudo but it should be as simple as:

ssh user@host "sudo -u scriptuser bash -c $cmd_str"

If you want, you can skip a step and avoid creating the intermediate variable:

$ ssh user@host "bash -c $(printf '%q' "$cmd")"
this really works

Or even just avoid creating a variable entirely:

ssh user@host "bash -c $(printf '%q' "[[ -f test ]] && echo 'this works as well'")"
share|improve this answer
this is an awesome solution. I've actually had to use printf before for a similar situation, but I always forget about it. Thanks for posting this :-) –  Jon L. Apr 23 at 7:26

You can define the script on your local machine and then cat and pipe it to the remote machine:

user@host:~/temp> echo "echo 'Test'" > fileForSsh.txt
user@host:~/temp> cat fileForSsh.txt | ssh localhost

Pseudo-terminal will not be allocated because stdin is not a terminal.
stty: standard input: Invalid argument
share|improve this answer
UUOC you can use < –  Iain Sep 2 '14 at 9:54
Can you modify the example to include sudo -u scriptuser? Would heredoc be usable considering I need to have variables in the script I'd be piping to the machine? –  VoY Sep 2 '14 at 10:36
I was trying: echo "sudo `cat fileForSsh.txt`" | ssh ... but I keep getting sudo: sorry, you must have a tty to run sudo. –  jas_raj Sep 2 '14 at 10:49
Although this question may help if you can get the /etc/sudoers file changed –  jas_raj Sep 2 '14 at 10:51
This works for me: ssh -tq user@host "sudo bash -s" < test.sh –  AVee Sep 4 '14 at 18:00

If you use a sufficiently modern Bash shell, you could put your commands in a function and print that function as a string using export -p -f function_name. The result of that string can then contain arbitrary commands that do not necessarily have to run as root.

An example using pipes from my answer on Unix.SE:

remote_main() {
   local dest="$HOME/destination"

   tar xzv -C "$dest"
   chgrp -R www-data "$dest"
   # Ensure that newly written files have the 'www-data' group too
   find "$dest" -type d -exec chmod g+s {} \;
tar cz files/ | ssh user@host "$(declare -pf remote_main); remote_main"

An example that retrieves saves the file for the login user and installs a program a root:

remote_main() {
    wget https://example.com/screenrc -O ~/.screenrc
    sudo apt-get update && sudo apt-get install screen
ssh user@host "$(declare -pf remote_main); remote_main"

If you would like to run the whole command using sudo, you could use this:

remote_main() {
    wget https://example.com/screenrc -O ~user/.screenrc
    apt-get update && apt-get install screen
ssh user@host "$(declare -pf remote_main);
    sudo sh -c \"\$(declare -pf remote_main); remote_cmd\""
# Alternatively, if you don't need stdin and do not want to log the command:
ssh user@host "$(declare -pf remote_main);
    (declare -pf remote_main; echo remote_cmd) | sudo sh"
share|improve this answer

Here is my (not really tested) crappy solution for this:

#!/usr/bin/env ruby
# shell-escape: Escape each argument.
ARGV.each do|a|
  print " '#{a.gsub("'","\'\\\\'\'")}' "

Not you can do:

ssh -tq myuser@hostname "$(shell-escape sudo -u scriptuser bash -c "$(shell-escape ls -al)")"

The next step is to create a betterssh script which already does this:

betterssh -tq myuser@hostname sudo -u scriptuser bash -c "$(shell-escape ls -al)"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.