Set up SSH key based authentication

SSH keys come in pairs: a public and a private key. It might be easier to think of them as a lock (public part) and key (private part). You add public key (lock) to the computer you want to connect to, and then you can connect from elswhere and unlock it with your private key. So public key is meant to be handed out freely, while private key should be kept secret and safely guarded.

So let's create an SSH key (all commands below are executed on your local computer, from which you will be connecting to remote example.com):

  1. Make sure local user has .ssh directory:

    mkdir -p ~/.ssh
    
  2. Generate SSH keys for passwordless authentication:

    ssh-keygen -b 4096 -f ~/.ssh/id_rsa_example
    

    You will be asked for a passphrase to locally encrypt your private key. It is highly recommended to do so. You could use SSH agent (like GNOME Keyring or KWallet) to cache this passphrase, so you don't have to enter it every time.

  3. Set key and config permissions to readable and writable by your user only:

    chmod -R u=rwX,go= .ssh
    
  4. Add public key to the server:

    ssh-copy-id -i ~/.ssh/id_rsa_example.pub user@example.com
    
  5. Test connection to add your server to known hosts list:

    ssh -i ~/.ssh/id_rsa_example user@example.com
    
  6. For easier use you could set connection settings in SSH client config. Config like this lets you connect with just ssh example.com:

    Host example.com
        User user
        IdentityFile ~/.ssh/id_rsa_example