An SSH command inside a script or a cron job has one nasty failure mode: it sits there and waits for someone to type a password that nobody will ever type. BatchMode turns the wait into an error.
The ssh_config manual describes BatchMode as follows: when set to yes, user interaction such as password prompts and host key confirmation requests is disabled. It is meant for scripts and batch jobs where no user is present. The default is no. You can set it per command with -o:
ssh -o BatchMode=yes -o ConnectTimeout=5 [email protected] uptime
ConnectTimeout is the second half of the habit. It sets a timeout in seconds for connecting, and the manual says it covers both the TCP connection and the initial SSH handshake, so a host that is switched off does not keep the script hanging for the default TCP timeout.
A small check that tells me if a box is reachable with my key:
if ssh -o BatchMode=yes -o ConnectTimeout=5 [email protected] true; then
echo "key login works"
else
echo "no key login (or host down)"
fi
The exit code of the remote true is the exit code of the whole command, and a failed login is a non-zero code, so the if does what it looks like.
The caveat is that a script can no longer ask you anything, and that includes the question about an unknown host key. A server you have never connected to will fail instead of prompting. Connect once by hand first, or add the key to known_hosts after checking its fingerprint. A key that is protected by a passphrase has the same problem, since nobody can type the passphrase. In that case the key has to be loaded into ssh-agent beforehand, or the job needs its own key without a passphrase, which I would treat with care.
You can also put BatchMode yes in a Host block of ~/.ssh/config for hosts that only scripts use.
Further reading: ssh_config(5): BatchMode and ConnectTimeout