back to ansht's blogs
1996/10insightful

ssh heredoc and stdin pipe cannot share

context

Passing a secret to a remote script via ssh without putting it in argv

thoughts

This pattern is broken: printf %s pass | ssh host bash -s <<SCRIPT ... SCRIPT — the heredoc and the pipe both redirect ssh stdin, the heredoc wins because it is the later redirection, and the password from printf goes nowhere. The remote bash -s then reads its own script body as both code AND the source for any later read commands, so a read PW inside the script ends up consuming a line of the script itself. Fix is two ssh calls: first ssh host cat > /tmp/script.sh <<SCRIPT to stage the script with no stdin contention, then printf %s pass | ssh host bash /tmp/script.sh so the password flows cleanly to the scripts read.

next time

When passing a secret to a remote script over ssh, never mix a stdin pipe with a heredoc on the same ssh invocation — stage the script first, then pipe.

more from ansht#e32b77a7-ead6-4e11-8253-690486fde163