There are many advantages to being able to access a remote system through ssh without requiring a password. Automating updates and backups with scripts is one example. Even the need to login into a system frequently is another example. Here, I’ll show you how to setup an RSA public/private key pair to authenticate the connection.
To get started, on your computer, you first need to create the RSA keys that will be used instead of a password. You only need to do this once. These keys will be used for all passwordless logins.
$ ssh-keygen -t rsa
The new keys can be found in
~/.ssh/id_rsa.pub. As the file extension indicates, the file
id_rsa.pub is the public key that will be shared with the server or remote computer. The file
id_rsa is the private key and should never be shared, ever!
Now that we have the keys, we need to share the public key with the server. The nice part about this is that we don’t need to add it to any configurations files. The key is shared by adding it to the
~/.ssh/authorized_keys file found in the home directory on the remote system of the user you want to login to.
# First create the remote users .ssh directory if it doesn't exist. $ ssh user@server mkdir -p .ssh # Next copy the public key to the server. $ cat .ssh/id_rsa.pub | ssh user@server 'cat >> .ssh/authorized_keys' # The permissions have to correct on the directory and the # authorized_keys file or ssh with reject them. $ ssh user@server "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
Now you should be able to login into the remote system without being asked for a password. Note that I said “should be able to”. Most ssh servers allow key authentication by default, but depending on the server admin, this can be turned off in the sshdconfig by setting the option PubkeyAuthentication to no. There really shouldn’t be any reason to do this, but I’m just warning you that it could still happen.
Here’s a simple bonus shell script to automate the whole process.
#!/bin/bash # # Copyright © 2019 Ron R Wills <email@example.com> # I give the right to all to use this for good and not evil. # # Usage: # ssh_keyauth user@remote # # Note this script is not very intelligent. If the public key already exists # on the remote system, it will be duplicated. # Check if we have a public key and create one if we don't. if [ ! -f ~/.ssh/id_rsa.pub ]; then ssh-keygen -t rsa || exit 1 fi # Create the files we need if necessary. ssh -t $1 <<EOF if [ ! -f ~/.ssh/authorized_key ]; then mkdir -p ~/.ssh chmod 700 ~/.ssh touch ~/.ssh/authorized_keys chmod 640 ~/.ssh/authorized_keys fi EOF test "x$?" = "x0" || exit 1 # Upload our public key. cat .ssh/id_rsa.pub | ssh -t $1 'cat >> .ssh/authorized_keys' || exit 1
See Also: ssh(1)