One of the greatest improvements introduced by the SSH protocol is key-based authentication – meaning your client and SSH server establish validity of your SSH keypair and let you gain remote SSH access without asking for your password.
SSH Authentication with Passwords
By default, SSH server will ask for your password when you're trying to connect. Unless you specify a username, your SSH client will set it automatically to your username on local (client) system:
In this example above, I'm running command line (iTerm2) session on my Macbook. greys is my local username, maverick is the hostname on my Macbook. I'm typing ssh command and specifying the server to connect to – with hostname becky.
As you can see, next thing that happens is that I get a password prompt.
How Key Based SSH Access Works
Key-based SSH authentication takes an extra step to setup but then saves you tons of time in the future:
- you deploy your public SSH key to remote server (need to type SSH password for possibly the last time)
- you start SSH agent to load your private SSH key and to use it for remote connections
- you connect to the remote SSH server without typing any passwords – still enjoying the same great benefits like encryption and traffic compression that SSH brings
Deploy Your Public SSH Key to Remote Server
You guessed it right! There's actually a command for that, it's called ssh-copy-id. What it does is connect to remote SSH server using username and password that you supply and then edit the .ssh/authorized_keys there to include your public key.
When running ssh-copy-id, you need to specify 2 things at a minimum:
- The SSH identity (name of a key you want to deploy)
- The SSH server name (where you want to add your key to)
Here's how it works:
greys@maverick:~ $ ssh-copy-id -i .ssh/id_ed25519 becky /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_ed25519.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys [email protected]'s password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'becky'" and check to make sure that only the key(s) you wanted were added.
Next time you attempt to connect, your ssh client will offer remote server a list of SSH identities you have configured on your client. In most recent Unix-like distros you have an SSH agent starting with your graphics login – it's called GNOME Keyring or or Keychain in MacOS (and there's plenty of ways to start ssh-agent during startups of sessions like KDE).
The bottom line is that when I try to connect to becky now, my SSH key is offered and, if it's available (loaded in ssh-agent), I get a passwordless SSH access to remote server:
That's it for today, have fun!