Here is a complete solution based on Eadwacer's answer:
#!/bin/bash
set -u
for ip in 1.1.1.1 2.2.2.2; do
ok=0
for try in {1..3}; do
echo "$ip: try #$try"
OUT="$(timeout -s KILL 30s ssh -o PreferredAuthentications=none "root@$ip" 2>&1)"
RES="$(echo "$OUT" | fgrep ': Permission denied (publickey).')"
if [ "$RES" != "" ]; then
ok=1
echo ' Auth is OK.'
break
else
echo ' Auth is BAD.'
fi
sleep 5
done
if [ "$ok" -eq 1 ]; then
echo "$ip: final result: OK"
else
echo "$ip: final result: FAIL" >&2
echo " ssh output: $OUT" >&2
fi
done
The retries are there to avoid false-positives due to intermittent connection failures like timeouts, etc.
Here is how a sample run looks like:
$ ./ssh-assert-key-auth-only.sh
1.1.1.1: try #1
Auth is OK.
1.1.1.1: final result: OK
2.2.2.2: try #1
Auth is BAD.
2.2.2.2: try #2
Auth is BAD.
2.2.2.2: try #3
Auth is BAD.
2.2.2.2: final result: FAIL
ssh output: [email protected]: Permission denied (publickey,password).
Debug info is sent to stdout
and can easily be muted for non-interactive runs:
$ ./ssh-assert-key-auth-only.sh >/dev/null
2.2.2.2: final result: FAIL
ssh output: [email protected]: Permission denied (publickey,password).
You have to replace 1.1.1.1
and 2.2.2.2
with the IP addresses or hostnames of your SSH servers. The string in fgrep
should also be edited if you want to accept something else than just "publickey".