Automating SSH Tasks with Bash
SSH (Secure Shell) is the standard way to work on remote Linux servers: it opens an encrypted connection, authenticates the user, and runs a shell or a single command on the remote machine. Typed by hand, ssh web1 opens an interactive session. Inside a script, ssh web1 COMMAND runs one command remotely and returns its output and exit status, which makes SSH the basic building block for automating work across servers: checking versions, collecting logs, restarting services, or deploying applications.
This lesson covers what changes when SSH is used from scripts instead of by a person: how a remote command is transmitted and why quoting works differently, how exit statuses report remote failures and connection failures, which options prevent a script from hanging at a prompt, how to send local scripts and files, and how to run a task on many servers in parallel. It assumes key-based authentication is already set up, because scripts cannot type passwords.
How SSH Runs a Remote Command
ssh deploy@web1 uptime
This command connects to the host web1, logs in as the user deploy, runs uptime there, prints its output locally, and exits with uptime's exit status. The important detail is how the command reaches the server. SSH does not send a list of arguments. It joins all words after the host name with single spaces into one string, sends that string, and the server runs it with the remote user's login shell, like bash -c "STRING". The command line is therefore parsed twice: once by the local shell, and once by the remote shell.
Double parsing and quoting
The consequences show with a file name containing a space. To make the remote parsing visible, the examples run the remote command printf '<%s>\n' ..., which prints each argument it receives between angle brackets:
file='My Report.txt'
ssh web1 printf "'<%s>\n'" $file
ssh web1 "printf '<%s>\n' $file"
ssh web1 "printf '<%s>\n' '$file'"
<My>
<Report.txt>
<My>
<Report.txt>
<My Report.txt>
In the first two commands, the local shell expanded $file, and the remote shell then split My Report.txt into two words. Quoting "$file" locally would not help: the quotes are removed by the local shell before SSH builds its string. The third command puts single quotes inside the string, so they reach the remote shell, which keeps the name together. That only works until a value contains a single quote itself:
f2="Bob's notes.txt"
ssh web1 "printf '<%s>\n' '$f2'"; echo "[status $?]"
bash: -c: line 1: unexpected EOF while looking for matching `''
[status 2]
The reliable solution is printf '%q', which turns any string into a form that Bash parses back into exactly that string:
printf '%q\n' "$f2" "$file" 'a$b'
ssh web1 "printf '<%s>\n' $(printf '%q' "$f2")"
Bob\'s\ notes.txt
My\ Report.txt
a\$b
<Bob's notes.txt>
%q produces Bash syntax; for some strings, such as ones containing newlines, it uses Bash's $'...' quoting. That is safe when the remote login shell is Bash, which is the default for users on most Linux servers. If it might be another shell, run the command through Bash explicitly, as the complete example does with bash -s.
Local and remote expansion
The same double parsing decides where a variable is expanded. In double quotes, the local shell expands it before SSH sends the string; in single quotes, the string reaches the server unchanged and the remote shell expands it:
ssh web1 "echo local: $HOSTNAME"
ssh web1 'echo remote: $HOSTNAME'
local: vm
remote: web1
vm is the name of the machine running the script. Mixing both kinds is common: ssh web1 "du -sh /var/log/$app" uses a local variable to build a command that runs remotely. Every value inserted this way should be quoted with printf '%q' if it can contain spaces or special characters, and must be if it comes from user input, because otherwise it is a command injection on the remote server (lesson 155).
Exit Statuses
ssh exits with the exit status of the remote command. When SSH itself fails, because the host is unreachable, the name cannot be resolved, authentication fails or the host key does not match, it exits with 255:
$ ssh db2 true; echo "[status $?]"
ssh: connect to host db2 port 22: Connection timed out
[status 255]
$ ssh web1 'exit 3'; echo "[status $?]"
[status 3]
Scripts can therefore distinguish "the server could not be reached" (255) from "the command ran and failed" (anything else). The distinction is only reliable if remote commands avoid 255 themselves.
Options for Unattended Use
Interactive SSH is designed to ask questions: for a password, for a key's passphrase, or whether to trust a host key it has never seen. A script that triggers one of these questions hangs until it is killed. The following options, given with -o or set in ~/.ssh/config, make SSH suitable for scripts:
| Option | Effect |
|---|---|
BatchMode=yes | never prompt for passwords or passphrases; fail with status 255 instead |
ConnectTimeout=10 | give up connecting after 10 seconds instead of waiting for the system's TCP timeout, which can take minutes |
StrictHostKeyChecking=accept-new | add keys of hosts never seen before to known_hosts automatically, but refuse to connect when a known host's key has changed (available since OpenSSH 7.6) |
ServerAliveInterval=15, ServerAliveCountMax=2 | send a keep-alive message every 15 seconds and disconnect after 2 unanswered ones, so a dead connection is detected instead of hanging forever |
The host key check deserves attention. The key identifies the server; a changed key can mean the server was reinstalled, but it can also mean the connection is being intercepted. StrictHostKeyChecking=no would accept changed keys silently and remove that protection, so it should not be used. For new servers, accept-new accepts the first key; alternatively, ssh-keyscan HOST >> ~/.ssh/known_hosts records keys in advance, ideally after comparing them with the fingerprints shown on the server's console.
Two more command-line flags matter in scripts:
-Tdisables the allocation of a remote terminal. A terminal is not needed for commands, and without one, the output contains plain\nline endings (the same effect asdocker run -tin lesson 175).-nconnects SSH's standard input to/dev/null.
SSH reads standard input
The -n flag prevents one of the most common SSH bugs in scripts. SSH forwards its standard input to the remote command, and it reads that input even when the remote command does not use it. In a loop that reads host names from a file, the first ssh therefore consumes the rest of the file:
while read -r host; do
ssh "$host" uptime # reads the remaining lines of hosts.txt
done < hosts.txt
The loop processes the first host and ends, without an error. ssh -n "$host" uptime, or ssh "$host" uptime < /dev/null, fixes it. Reading the list into an array first (lesson 97), as the complete example does, avoids the problem entirely.
~/.ssh/config
Options that apply to every connection, or to a group of hosts, can be stored in ~/.ssh/config instead of being repeated in every command:
Host web* db*
User deploy
IdentityFile ~/.ssh/deploy_ed25519
BatchMode yes
ConnectTimeout 10
StrictHostKeyChecking accept-new
ServerAliveInterval 15
Host *
ControlMaster auto
ControlPath ~/.ssh/cm-%r@%h:%p
ControlPersist 60s
The last block enables connection sharing. Establishing an SSH connection takes a noticeable fraction of a second because of the key exchange and authentication. With ControlMaster auto, the first connection to a host creates a socket at ControlPath (%r, %h and %p are replaced by user, host and port), and later ssh commands to the same host reuse that connection. ControlPersist 60s keeps it open for 60 seconds after the last use. A script that runs many short commands on the same server becomes much faster.
Sending Scripts and Data
Running a local script remotely
Anything longer than a short command is easier to maintain as a script file on the local machine, where it can be edited and checked. bash -s makes Bash read its program from standard input, so a local script can be run remotely without copying it there first:
ssh web1 'bash -s' < check-version.sh
Arguments for the script follow bash -s --. Like any part of the remote command, they are joined into the string and parsed by the remote shell, so they must be quoted with %q:
set -- "release notes.txt" "Bob's file" '$HOME'
remote_cmd="bash -s --${*:+ $(printf '%q ' "$@")}"
echo "$remote_cmd"
bash -s -- release\ notes.txt Bob\'s\ file \$HOME
${*:+ ...} adds the quoted arguments, with a leading space, only if there are any. A test script that prints its arguments, run this way, received all three exactly as given, including the literal $HOME (see the complete example).
Files and command output
Standard input and output also carry data. Combined with a pipe, SSH copies files without any extra tool, and runs commands whose output is used locally:
ssh web1 'cat > app/config.ini' < config.ini # upload a file
ssh web1 'tar -czf - -C /var/log/app .' > web1-logs.tar.gz # download a directory as an archive
ssh db1 'pg_dump shop' | gzip > shop-$(date +%F).sql.gz # remote command, local compression
For regular file transfers, scp and rsync are the usual tools; rsync -a --delete src/ host:/path/ transfers only differences and is the standard way to synchronize directories. Both use SSH underneath and accept the same configuration.
Running a Task on Many Servers
Running a command on twenty servers one after another takes twenty times as long as one, and a single unreachable server can stall the loop for the connection timeout. Running the connections as background jobs (lesson 136) in parallel solves both, with three rules: limit how many run at once, so that neither the local machine nor a shared service is overwhelmed; give every host a time limit; and keep each host's output in its own file instead of interleaving it.
Bash 5.1 added the option -p to wait -n: wait -n -p var waits for the next background job to finish, returns its exit status, and stores its process ID in var. With a table that maps process IDs to hosts, the script learns which host finished and how.
A Complete Example: Running Commands on a Fleet of Servers
remote-run.sh runs a command, or a local Bash script with arguments, on every host in a host file, with a limit on parallel connections and a time limit per host. Each host's output goes to a log file, and the script ends with one line per host and an overall exit status.
#!/usr/bin/env bash
#
# remote-run.sh - run a command or a local script on many hosts over SSH
#
# Usage: remote-run.sh [-j JOBS] [-t SECONDS] [-l DIR] HOSTFILE -c 'COMMAND'
# remote-run.sh [-j JOBS] [-t SECONDS] [-l DIR] HOSTFILE -s SCRIPT [ARG...]
# -j JOBS hosts processed at the same time (default: 4)
# -t SECONDS time limit per host (default: 60)
# -l DIR directory for per-host output logs (default: ./remote-logs)
# -c COMMAND run COMMAND with the remote user's shell
# -s SCRIPT send the local Bash script SCRIPT and run it remotely with ARGs
#
# HOSTFILE lists one host per line ([user@]host); # starts a comment.
# Exit status: 0 if every host succeeded, 1 otherwise, 2 for usage errors.
set -uo pipefail
usage() {
echo "usage: ${0##*/} [-j JOBS] [-t SECONDS] [-l DIR] HOSTFILE -c 'COMMAND'" >&2
echo " ${0##*/} [-j JOBS] [-t SECONDS] [-l DIR] HOSTFILE -s SCRIPT [ARG...]" >&2
exit 2
}
jobs=4 limit=60 logdir=./remote-logs
while getopts ':j:t:l:' opt; do
case $opt in
j|t) [[ $OPTARG =~ ^[1-9][0-9]*$ ]] || usage ;;&
j) jobs=$OPTARG ;;
t) limit=$OPTARG ;;
l) logdir=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# >= 3 )) || usage
hostfile=$1 mode=$2
shift 2
case $mode in
-c) (( $# == 1 )) || usage; remote_cmd=$1; script='' ;;
-s) script=$1; shift
[[ -r $script ]] || { echo "${0##*/}: cannot read $script" >&2; exit 2; }
# the arguments travel as text and are parsed by the remote shell: quote them
remote_cmd="bash -s --${*:+ $(printf '%q ' "$@")}" ;;
*) usage ;;
esac
mapfile -t hosts < <(sed -e 's/#.*//' -e 's/[[:space:]]//g' -e '/^$/d' "$hostfile")
(( ${#hosts[@]} )) || { echo "${0##*/}: no hosts in $hostfile" >&2; exit 2; }
mkdir -p "$logdir" || exit 2
# Options for unattended use: never prompt, fail fast, notice dead connections
ssh_opts=(
-o BatchMode=yes
-o ConnectTimeout=10
-o StrictHostKeyChecking=accept-new
-o ServerAliveInterval=15 -o ServerAliveCountMax=2
-T
)
# run_host HOST: run the task on one host; the output goes to its log file
run_host() {
local host=$1 log=$logdir/${1//[^A-Za-z0-9._@-]/_}.log
if [[ -n $script ]]; then
timeout "$limit" ssh "${ssh_opts[@]}" "$host" "$remote_cmd" < "$script" > "$log" 2>&1
else
timeout "$limit" ssh "${ssh_opts[@]}" -n "$host" "$remote_cmd" > "$log" 2>&1
fi
}
describe() { # describe STATUS: explain an exit status
case $1 in
0) echo ok ;;
124) echo "TIMEOUT after ${limit}s" ;;
255) echo "SSH ERROR (connection or login failed)" ;;
*) echo "FAILED with exit status $1" ;;
esac
}
declare -A pid_host=() result=()
running=0
for host in "${hosts[@]}"; do
if (( running >= jobs )); then # wait for a free slot
wait -n -p done_pid; status=$?
result[${pid_host[$done_pid]}]=$status; running=$(( running - 1 ))
fi
run_host "$host" &
pid_host[$!]=$host; running=$(( running + 1 ))
done
while (( running > 0 )); do
wait -n -p done_pid; status=$?
result[${pid_host[$done_pid]}]=$status; running=$(( running - 1 ))
done
# report in host-file order, with the last line of each host's output
failed=0
for host in "${hosts[@]}"; do
status=${result[$host]}
(( status == 0 )) || failed=$(( failed + 1 ))
log=$logdir/${host//[^A-Za-z0-9._@-]/_}.log
printf '%-12s %-40s %s\n' "$host" "$(describe "$status")" "$(tail -n 1 "$log")"
done
echo "${#hosts[@]} hosts, $(( ${#hosts[@]} - failed )) ok, $failed failed; logs in $logdir"
(( failed == 0 ))
How It Works
- Two modes. With
-c, the command string is passed tosshas one argument and parsed by the remote shell, which is what the user writes it for. With-s, the script file becomes SSH's standard input and the remote command isbash -s --followed by the arguments, each quoted withprintf '%q', so they arrive unchanged however many spaces, quotes or dollar signs they contain. - Reading the host file.
sedremoves comments, whitespace and empty lines, andmapfile(lesson 114) loads the hosts into an array before any connection is made, so nosshcan consume the host list. - Unattended SSH options are kept in one array and used for every connection. In
-cmode,-nkeeps SSH away from the script's standard input; in-smode, standard input is the script file, as intended. - Two time limits.
ConnectTimeoutlimits connecting;timeout "$limit"(lesson 142) limits the whole task, including a remote command that hangs.timeoutexits with 124 when it had to stop the command, whichdescribereports separately from SSH errors (255) and failures of the remote command. - A bounded pool of parallel jobs. Each host runs in a background job. When
jobsconnections are running,wait -n -p done_pidwaits for any one of them to end; the associative arraypid_hostmaps its process ID back to the host, and the exit status is stored inresult. The final loop waits for the remaining jobs the same way.wait -n -prequires Bash 5.1 or later. - Safe log names.
${1//[^A-Za-z0-9._@-]/_}replaces every character that is unusual in a file name with_, so a host entry cannot produce a path outside the log directory. - The report follows the order of the host file, not the order in which hosts finished, and shows the last line of each host's output, which is usually the most informative one. The detailed output stays in the logs.
Running the Complete Example
The script was tested on a machine without real servers, using the technique of lesson 186: a stand-in program named ssh, placed first in PATH, behaves like SSH towards the script. It accepts the same options, joins the remote command's words and has Bash parse them in a directory that plays the role of each host's home directory, and it simulates failures: db2 fails to connect with status 255 and SSH's real error message, and web3 never answers. The script itself cannot tell the difference, which is exactly what makes this a useful way to test SSH automation before running it against production servers.
The host file:
# application servers
web1
web2
web3 # new server
db2
deploy@web4
The task checks the application version deployed on each server and the free disk space, with a local script that receives the expected version as an argument:
#!/usr/bin/env bash
# check-version.sh EXPECTED [MIN_FREE_MB]: runs on a server; checks the deployed
# application version and the free space in the home directory
set -u
expected=$1 min_free=${2:-100}
version=$(< app/VERSION) || exit 1
free=$(df -Pm . | awk 'NR == 2 { print $4 }')
echo "host $HOSTNAME: version $version, ${free} MB free"
[[ $version == "$expected" ]] || { echo "version $version, expected $expected"; exit 1; }
(( free >= min_free )) || { echo "only ${free} MB free, need $min_free"; exit 1; }
echo "version $version ok"
With a time limit of 5 seconds per host:
$ remote-run.sh -t 5 hosts.txt -s check-version.sh 2.4.1
web1 ok version 2.4.1 ok
web2 FAILED with exit status 1 version 2.4.0, expected 2.4.1
web3 TIMEOUT after 5s
db2 SSH ERROR (connection or login failed) ssh: connect to host db2 port 22: Connection timed out
deploy@web4 ok version 2.4.1 ok
5 hosts, 2 ok, 3 failed; logs in ./remote-logs
[status 1 after 5s]
$ cat remote-logs/web2.log
host web2: version 2.4.0, 30519 MB free
version 2.4.0, expected 2.4.1
The three kinds of failure are reported differently: web2 was reached and its check failed, db2 could not be reached, and web3 did not finish in time. All five hosts were processed in parallel, so the whole run took 5 seconds, the time limit of the slowest host. With -j 1, the hosts run one after another; the run took 3 seconds with a 2-second limit, the sum of web3's timeout and db2's connection failure:
$ remote-run.sh -j 1 -t 2 hosts.txt -c true
web1 ok
web2 ok
web3 TIMEOUT after 2s
db2 SSH ERROR (connection or login failed) ssh: connect to host db2 port 22: Connection timed out
deploy@web4 ok
5 hosts, 3 ok, 2 failed; logs in ./remote-logs
[status 1 after 3s]
In command mode, the remote shell parses the string, so remote variables such as $HOSTNAME are expanded on each host:
$ remote-run.sh -l logs2 web.txt -c 'cat app/VERSION && echo "up on $HOSTNAME"'
web1 ok up on web1
web4 ok up on web4
2 hosts, 2 ok, 0 failed; logs in logs2
To verify the argument quoting, a script that prints each of its arguments in angle brackets was run with three difficult arguments. All three arrived exactly as given:
$ cat show-args.sh
for a; do printf "<%s>\n" "$a"; done
$ remote-run.sh -l logs3 web.txt -s show-args.sh "release notes.txt" "Bob's file" '$HOME'
web1 ok <$HOME>
web4 ok <$HOME>
2 hosts, 2 ok, 0 failed; logs in logs3
$ cat logs3/web1.log
<release notes.txt>
<Bob's file>
<$HOME>
Usage errors exit with status 2 before any connection is made:
$ remote-run.sh -j 0 hosts.txt -c true
usage: remote-run.sh [-j JOBS] [-t SECONDS] [-l DIR] HOSTFILE -c 'COMMAND'
remote-run.sh [-j JOBS] [-t SECONDS] [-l DIR] HOSTFILE -s SCRIPT [ARG...]
[status 2]
$ remote-run.sh hosts.txt -s nosuch.sh
remote-run.sh: cannot read nosuch.sh
[status 2]
Because the script exits with 1 when any host failed, it can be used in larger automation, for example as a check after a deployment, or from cron with a notification on failure (lesson 173).