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 THEREDouble 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
EOFbash -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.txtThis 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" trueBatchMode=yes— never prompt. Password prompts in a cron job hang forever; fail instead.ConnectTimeout=5— bounds dead-host detection, layered under yourtimeout 300.StrictHostKeyChecking=accept-new— TOFU: accept the first key, refuse changes.yesis the insecure default juniors reach for;nois how you do MITM-by-turkey. OpenSSH has hadaccept-newsince 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 10mFirst 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.txtThen 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 cmdreturns the remote command's exit status — butsshitself returns255for connection failures; distinguish "remote failed" from "couldn't reach" when alerting.- TTY: commands needing one (
sudowithout-n,top) needssh -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/tmuxsurvive roaming and resume, but that's interactive persistence — automation wantsBatchMode+ retries, not session resumption.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Red Hat Called This Bug a 5.9. Two Weeks Later It Was a 9.8.
CVE-2026-98432 is a use-after-free in the IPv4 TCP handshake, reachable by anybody who can reach a listening port, sitting in the kernel since 4.4. Red Hat scored it 5.9 moderate and deferred the fix. Then 8.1. Then 9.8.
Self-Host OpenClaw: VPS Setup to Production (2026)
Self-host OpenClaw from zero to production. Server provisioning, SSH lockdown, Docker, reverse proxy, Fail2ban, performance tuning, and full backup strategy in one guide.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.