If you are setting up a new server or configuring a new account it can be a pain to setup ssh public key authentication so you don’t have to use passwords. The most difficult part is transferring your private key to the remote machines. Fortuneatly there is an easy way to accomplish this task.
The first step is to generate a rsa public and private keypair on your local machine.
Now you will need to transfer your local public key to each remote machine that you would like access. There are a couple ways to do this.
1) If your local machine has the ssh-copy-id utility installed, you can copy it to the remotehost with one simple command.
$ ssh-copy-id -i ~/.ssh/id_rsa.pub remotehost
ssh-copy-id will append your public key to ~/.ssh/authorized_keys on the remote machine, creating the file and directory if necessary.
Some notes about ssh-copy-id:
- ssh-copy-id uses ~/.ssh/identity.pub as the default public key file (i.e when no value is passed to option -i).
- If the operation fails and
$ ssh-add -Lreturns
The agent has no identitiesthe ssh-copy-id will still copy the message “The agent has no identities” to the remote-host’s authorized_keys entry. You will need to use the second method below.
- If you execute ssh-copy-id multiple times it will keep appending the same key on the remote-host’s authorized_keys file without checking for duplicates. Even with duplicate entries everything works as expected but it is still not the best implementation.
2) If you are lacking ssh-copy-id or the fisrt method fails you can use ssh to accomplish the same task.
ssh remotehost 'cat >> ~/.ssh/authorized_keys' < ~/.ssh/id_rsa.pub
You can now log in without password.
$ ssh remotehost