Mini Builds

Creating and Using SSH Keys

May 8, 2021

SSH keys are a secure way to conveniently log into another machine. This guide shows how to create a key pair, set up the ssh agent and copy the public key to a remote server.

Create a key pair

The command below will create a key pair. It will prompt for:

ssh-keygen

Start the SSH agent

The SSH agent is a key manager that keeps keys in memory saving you from typing if your passphrase every time you use your key.

eval `ssh-agent -s`

Add the key to the SSH agent

This is load a key into memory for use by ssh. You’ll be asked for the passphrase.

ssh-add ~/.ssh/id_rsa

Copy the key to the remote machine

You can now copy the public part of the key pair to another machine. The command below associates the key with a user on the host machine. You will be asked for the password of the user on the host.

ssh-copy-id -i ~/.ssh/id_rsa user@host

If successfully you’ll get a message stating you added the key e.g. Number of key(s) added: 1.

Give it a go

ssh user@host

Automatically start the SSH agent

The SSH agent will only keep a key in memory for as long as the process that it was started in is alive. Adding the following script to ~/.bashrc will start the SSH agent and add default keys e.g. ~/.ssh/id_rsa to the agent every time a shell is opened (if not already added).

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
  (umask 077; ssh-agent >| "$env")
  . "$env" >| /dev/null ;
} 

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running

agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
  agent_start
  ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
  ssh-add
fi

unset env

Host Short Names in SSH Config

For convenience you can set up an SSH config file (~/.ssh/config) which details short names for host, user and key. So instead of ssh dev.minibuilds.io you can simply type ssh dev.

Host dev
	HostName dev.minibuilds.io
	User minibuilds
	IdentityFile ~/.ssh/id_rsa

# ... other hosts

This can be particularly handy for accessing multiple machines or machines with long or difficult to remember host addresses.