2

Here is my use case: I have a script that lists through hundreds of servers and tests whether or not they allow logins using public key authentication using a specific private key (in the ssh client's .ssh directory). Some of these servers were misconfigured, and I do not have control over the SSH service on any of these servers.

Here is what I have so far:

ssh -o ConnectTimeout=2 -o PasswordAuthentication=no -q $x exit
returncode=$?

So this works so far for most servers (i.e., returns a non-zero return code when a server is unreachable, and 0 when the server can be logged-in to), until some troublesome server fails due to some SSH misconfiguration (ex. ~/.ssh on the remote server has an incorrect permission. Here is a related thread describing what can be done in such case.

But i don't want to fix the remote servers. I just want SSH to fail and exit with a non-zero return code if SSH key authentication fails.

Any ideas how to get around this?

Thanks in advance.

5
  • Try adding -o IdentitiesOnly=yes option
    – Tagwint
    Jan 29 '20 at 14:43
  • The title suggests that ssh (in some circumstances?) asks for password despite PasswordAuthentication=no and this is the problem. The question body suggests that ssh in some circumstances fails (returns non-zero exit status) despite the fact the key matches, and this is the problem. In the latter case no password is involved at all. Or do I get it wrong? For now I'm confused, I don't know which problem is the problem. Please edit and clarify. Jan 29 '20 at 15:41
  • Take a look at Ansible, seems perfect for this task
    – M_dk
    Jan 29 '20 at 16:09
  • 1
    There IS a -o batchmode=yes option to avoid ssh asking anything. (Esther confirming signature or asking password)
    – Archemar
    Jan 30 '20 at 9:32
  • @Archemar please post as an answer, it looks useful and would be a more decent approach IMO as it would not involve another command.
    – Lester
    Jan 30 '20 at 12:24
3

You can use timeout in addition to limit ssh's runtime:

timeout 10 ssh -o ConnectTimeout=2 -o PasswordAuthentication=no -q $x exit returncode=$?

or

timeout --preserve-status 10 ssh -o ConnectTimeout=2 -o PasswordAuthentication=no -q $x exit returncode=$?

Be sure to choose a good timeout. 2 seconds ConnectTimeout plus 8 seconds for running exit sould be enough; even on high load.

1
  • great, works perfectly.
    – Lester
    Jan 29 '20 at 15:46
1

As per suggestion,

ssh has a -o batchmode=yes option that will prevent any interaction.

  • no password asked

  • no confirmation for foreign signature

This will result in error code if no connection is make.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.