How to check if I can log in to server via ssh?
You can do that with a combination of the BatchMode
option and "parsing" the output. (ssh
always returns 255 if it fails to connect for whatever reason, so you can't use the return code to distinguish between types of failures.)
With BatchMode
on, no password prompt or other interaction is attempted, so a connect that requires a password will fail. (I also put a ConnectTimeout
in there which should be adjusted to fit your needs. And picked really bad filenames.)
#! /bin/bash
rm good no_auth other
while read ip host ; do
status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 $ip echo ok 2>&1)
case $status in
ok) echo $ip $host >> good ;;
*"Permission denied"*) echo $ip $host $status >> no_auth ;;
*) echo $ip $host $status >> other ;;
esac
done < list.txt
You could detect other types of errors (like missing server public key) if you need more detailed classification. If you need the results in a single, sorted file, just cat
the various output files together as you see fit.