brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ssh -o BatchMode=yes makes scripts fail instead of waiting for a password

Network and access
~/tips/tip-ssh-batchmode-scripts

ssh -o BatchMode=yes -o ConnectTimeout=5 [email protected] uptime

Stops ssh from asking for passwords or confirmations, so a script fails fast instead of hanging.

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

More Network and access tips scp -3 alice@server-a:/var/backups/db.sql.gz bob@server-b:/srv/restore/ tailscale exit-node suggest tailscale lock sign nodekey:1abddef1 tlpub:abcdef12 wg genpsk > peer1.psk Table = off All Network and access tips (163) All topics

Link