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-thingy
returns a non-zero exit status if no public key matches on the remote host.
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).