Skip to content

Instantly share code, notes, and snippets.

@shvchk
Created May 19, 2017 23:15
Show Gist options
  • Save shvchk/2f1c02ebf2ffad084b5abad1ceff9eec to your computer and use it in GitHub Desktop.
Save shvchk/2f1c02ebf2ffad084b5abad1ceff9eec to your computer and use it in GitHub Desktop.

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 be readable and writable by your user only:

    chmod -R 600 ~/.ssh

  4. Add public key to the server:

    ssh-copy-id -i ~/.ssh/id_rsa_example.pub [email protected]

  5. Test connection to add your server to known hosts list:

    ssh -i ~/.ssh/id_rsa_example [email protected]

  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
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment