12

Is there a way to programmatically test whether ssh can authenticate using a public key? I would like to do something like this (preferably in bash, but am open to a python solution):

ssh-test-thingy user@host || echo "could not authenticate using publickey"

where ssh-test-thingyreturns a non-zero exit status if no public key matches on the remote host.

pihentagy
  • 5,975
  • 9
  • 39
  • 58
Bacon
  • 2,155
  • 4
  • 23
  • 31

1 Answers1

18

I'd pass the option -o BatchMode=yes to ssh and see if that works. It will disable prompting for a password, which I think is equivalent in practice to your desire to find out if authentication via keys is possible. ssh-test-thingy could be written as a bash script like so:

exec ssh -o BatchMode=yes "$@" true

This will simply pass the user@host (and any other arguments) along, and try to run true on the remote host, which if it works will immediately return a status code of success (0).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    I had to put "true" at the end of the command to get it to work, example: ssh -o BatchMode=yes "$@" true – Joseph Lisee Apr 04 '12 at 19:29
  • 1
    Adding `-q` makes it quiet. – javs May 30 '13 at 15:33
  • What is the purpose of the `exec`? – pihentagy Apr 03 '14 at 11:49
  • @pihentagy: `exec` replaces the current shell process with the ssh process. This is OK because the shell is not needed any more after ssh is launched; the return value of the program should be the return value of ssh. You could return what ssh returns without the exec, but why bother spawning one more process you don't need? – John Zwinck Apr 03 '14 at 14:11
  • I blindly copy-pasted the solution to a function of a script, and it did not work with exec. – pihentagy Apr 03 '14 at 18:58
  • If you're going to put it in a function, you would need to remove the "exec" part, yes. I wrote it that way for it to be an entire script by itself, not a function. – John Zwinck Apr 04 '14 at 02:02
  • This assumes the "true" will get executed. First problem that comes to mind is if the account is forcing a password reset. – Ron Burk Apr 20 '16 at 05:42