ssh has a "BatchMode" option which will make it simply fail rather than asking for a password. This seems much easier than having your script try to predict whether it will ask for a password. An answer to a similar question on SuperUser points out that merely disabling PasswordAuthentication won't always work because there are multiple different interactive authentication types, and it also doesn't look like it'll stop it from prompting for a passphrase on a key.
You can use ssh -o BatchMode=yes
, or put it in your ssh_config for the host.
Also, ssh won't prompt for a password if there is no controlling terminal (it gets an error "read_passphrase: can't open /dev/tty: No such device or address
") - you can start a process with no controlling tty with setsid
, which you should ideally do when you start Jenkins rather than doing it specifically for the ssh command (this will also prevent sudo
from prompting for a password, etc)
Note that if you run a process with setsid
it will automatically run in the background (since the shell can't work with job control with processes in different sessions), so you need to be prepared for this by redirecting its stdout/stderr to a log file (and stdin to /dev/null). You can get strange results if a program run in setsid
tries to read anything at all from standard input, since the usual mechanisms for preventing a background process from reading the terminal don't work.