I’m writing an unattended shell script that sets up a new server. Since I may run it multiple times, I want to check whether passwordless SSH access has already been set up. A command like
ssh newhost.example.com /bin/true
will exit successfully if the access exists, but if not, it will hang waiting for a password to be entered.
Is there a way to turn off the possibility of password access for such a command so that it will quickly fail if passwordless access is not yet set up?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can turn off the PasswordAuthentication option:
ssh -o PasswordAuthentication=no newhost.example.com /bin/true
This does not prompt for a password and quickly returns exit code 255 when passwordless access is denied.
Method 2
To tell ssh that you only want to use public key authentication, use the PreferredAuthentications configuration option.
Interactively:
ssh -o PreferredAuthentications=publickey newhost.example.com /bin/true
Or in the ~/.ssh/config file:
# or Host *.example.com, or Host *
Host newhost.example.com
PreferredAuthentications=publickey
Method 3
With ssh -o PasswordAuthentication=no newhost.example.com /bin/true you still risk the chance of hitting an interactive question:
$ ssh -o PasswordAuthentication=no newhost.example.com /bin/true The authenticity of host 'newhost.example.com (a.b.c.d)' can't be established. ECDSA key fingerprint is SHA256:<fingerprint>. Are you sure you want to continue connecting (yes/no)?
A better option, IMHO, is to run ssh in BatchMode:
$ ssh -o BatchMode=yes newhost.example.com /bin/true Host key verification failed. $ echo $? 255
If you have ssh passwordless login configured and working, ssh would not need to check the fingerprint and you should see it working.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0