your way of checking whether an SSH key is setup is very bad.
- It can fail (e.g, when the connection takes more than 5s to establish, or when the shell of the user doesn't understand "exit", or when anything else doesn't happen within 5s) even if the user has a SSH key set up,
- and it can succeed even when the user hasn't (when the connection gets established in less than 5s and the user enters a password quick enough, which is quite commonly the case!), or if there's already a connection established,
- and it potentially leaves half-finished SSH connections lying around.
You need to replace that method. It simply doesn't do it's job.
That's rather easy, tell SSH to not allow password authentication; depending on your version of SSH, there's an option for that (man ssh
); most likely a
ssh -n -oControlMaster=no \
-oPasswordAuthentication=no \
-oKbdInteractiveAuthentication=no \
-oPreferredAuthentications=publickey \
user@host true \
|| \
echo "can't log in"
does what you want, without any of the bad ideas involving timeouts and so on. Thing works, or it fails.
Problem: it will print the same, no matter whether you couldn't connect to the host, or whether you could not authenticate. Those are different things.
by the way, if the whole thing is just meant to enable users to make sure they've got publickey auth set up: There's the ssh-copy-id user@host
, which tries to log in (how ever possible), and then checks whether the user's public key is installed on the server. That would probably obsolete your whole script :)