Skip to content

Lesson 13 of 14 · 16m

SSH and the Second Shell Parse

Quoting across two shells, the stdin-eating loop, BatchMode and ControlMaster for fleets, and bash -s for remote scripts.

ssh web-01 'systemctl restart app' looks like one command. It's two shell parses: your local shell builds one argument string, ships it over the wire, and the remote shell parses it again. Everything about SSH scripting pain — the empty variables, the eaten loops, the quoting that "worked in testing" — is that second parse doing exactly what you told it to do, on the wrong machine.

Which shell expands your variable

dir=/var/log/app
ssh web-01 "tar czf - $dir"     # local expand → remote sees tar czf - /var/log/app
ssh web-01 'tar czf - $dir'     # remote expands → remote sees $dir's value THERE

Double quotes expand locally, before the string leaves. Single quotes ship $dir to the remote, which expands it against its environment — usually empty. Neither is wrong in general; both are wrong when you meant the other one. The correct generalization: quote for the machine that should see the data. To pass a local value into a remote command safely, hand it as an argument rather than interpolating:

ssh web-01 bash -s -- "$dir" << 'EOF'
set -euo pipefail
dir=$1
tar czf - "$dir" | sha256sum
EOF

bash -s reads the script from stdin; -- "$dir" lands the value in $1 on the remote side, where quoting is normal again. This is the shape for "run a non-trivial script on a box" — one heredoc, one argument list, no nested-quote surgery.

The stdin-eating loop

while read -r host; do
  ssh "$host" uptime
done < hosts.txt

This runs once. ssh reads its stdin — which is the loop's stdin — and drains hosts.txt on the first pass. ffmpeg does the same inside while read. The fix is ssh -n (ssh's stdin from /dev/null) or < /dev/null on the command. Quarter-century-old bug class, still tripping people weekly — memorize it.

Options that matter for automation

ssh -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new "$host" true
  • BatchMode=yes — never prompt. Password prompts in a cron job hang forever; fail instead.
  • ConnectTimeout=5 — bounds dead-host detection, layered under your timeout 300.
  • StrictHostKeyChecking=accept-new — TOFU: accept the first key, refuse changes. yes is the insecure default juniors reach for; no is how you do MITM-by-turkey. OpenSSH has had accept-new since 7.6 (2017).
  • -J bastion — ProxyJump through a bastion in one hop instead of nested ssh.
  • -o UserKnownHostsFile=/etc/ssh/known_hosts_fleet — pin a fleet file rather than per-user state.

ControlMaster: one TCP, many shells

Forty hosts each need ten commands. Without reuse, that's four hundred handshakes — TCP, key exchange, auth — each costing 100-500ms before the command runs:

# ~/.ssh/config or -o flags
Host web-*
  ControlMaster auto
  ControlPath ~/.ssh/cm-%r@%h:%p
  ControlPersist 10m

First ssh to a host builds a master connection; every later ssh/scp/rsync to the same host multiplexes over it in milliseconds. ControlPersist 10m keeps the master warm after you disconnect. Check with ssh -O check host, kill with ssh -O exit host. The catch worth knowing: a stale master (suspended laptop, dead remote) makes new connections hang until the socket file is cleaned — ControlPath under ~/.ssh/ makes it your problem to rm when wedged.

Moving data: cat over ssh, then rsync

ssh web-01 'cat > /etc/app/app.conf' < app.conf     # stream a file through stdin
ssh web-01 'cat /var/log/app.log' | grep -c 500     # remote data, local pipeline
rsync -az --partial -e 'ssh -J bastion' logs/ web-01:/srv/logs/

cat over ssh beats scp for scripted single files — stdin/stdout compose with pipes, no extra tooling. rsync -e ssh handles trees, resumes with --partial, and composes with -J for bastions. -z compression earns its CPU on text logs; skip it for already-compressed media.

Try this

hosts=(web-01 web-02)
while read -r host; do
  ssh -n -o BatchMode=yes -o ConnectTimeout=3 "$host" 'hostname; uptime'
done < hosts.txt

Then flip -n off and watch the loop stop after one host. Finally, add ControlMaster config and time for i in {1..10}; do ssh web-01 true; done before and after — the multiplexed runs land in milliseconds.

Pitfalls

  • ssh host cmd returns the remote command's exit status — but ssh itself returns 255 for connection failures; distinguish "remote failed" from "couldn't reach" when alerting.
  • TTY: commands needing one (sudo without -n, top) need ssh -t; allocating a TTY for batch work just adds a pty in the middle — omit it.
  • ~ and unquoted globs expand on whichever side of the parse they land — ssh host 'ls /srv/*.log' remote-glob, ssh host "ls $HOME" local-expand. Pick deliberately.
  • mosh/tmux survive roaming and resume, but that's interactive persistence — automation wants BatchMode + retries, not session resumption.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.