How do I make ssh fail rather than prompt for a password if the public-key authentication fails?

Solution 1:

For OpenSSH there is BatchMode, which in addition to disabling password prompting, should disable querying for passphrase(s) for keys.

BatchMode

If set to “yes”, passphrase/password querying will be disabled. This option is useful in scripts and other batch jobs where no user is present to supply the password. The argument must be “yes” or “no”. The default is “no”.

Sample usage:

ssh -oBatchMode=yes -l <user> <host> <dostuff>

Solution 2:

  • To disable password authentication for the current ssh connection attempt, pass this option on the command line:

    -o PasswordAuthentication=no
    
  • To disable password authentication for all future connections to any host add the following to your ~/.ssh/config:

    PasswordAuthentication no
    
  • To disable it for just some hosts, add the following to ~/.ssh/config:

    Host host1 host2 host3...
        PasswordAuthentication no
    

The options above apply to out-going ssh connections, i.e. where you're trying to connect to a remote ssh server.

To disable password authentication on an ssh server (i.e. applies to all incoming ssh connections), add PasswordAuthentication no to /etc/ssh/sshd_config and restart sshd.


Solution 3:

If you are using dropbear, just add the "-s" option to disable password authentication.


Solution 4:

On the command line (or ~/.ssh/config) you can set PreferredAuthentications.

PreferredAuthentications=publickey

Solution 5:

Here is a sample sftp bash script snippet. I am using "-o BatchMode=Yes" to disable the password prompt in case of failure. And check the frp return code to check if the ftp connection failed.

sftp -o "IdentityFile=<YOUR_IDENTTIY_FILE>"  -o "BatchMode=Yes" [email protected] <<EOF

cd /$remotepath
mget *.csv $localpath/download

quit
EOF
exit_code=$?
if [[ $exit_code != 0 ]]; then
   echo "sftp error, failed to connect to ftp server" >&2
   exit 1
fi