How to Generate an SSH Keypair
Learn how to create an SSH keypair on Linux and use it for passwordless, secure login to remote Linux servers
Many deployment tools use SSH to connect with, and install software on target hosts. In some cases, they insist that SSH be enabled with passwordless login, using public/private keypairs.
This kind of login is seamless — instead of asking for a password, the server accepts an encrypted copy of the user’s private key and compares this with the user’s public key, normally stored on the server in a file called authorized_keys in the user’s /home/user/.ssh directory.
ssh -i ~/.ssh/id_rsa <user>@<ip_address>
The private key is often called id_rsa, and is canonically stored in the user’s .ssh directory on the server as well.
Prerequisites
To generate an SSH keypair, all you need is a computer or virtual machine running a Linux distribution (in this tutorial, we’re using Ubuntu). This is likely a machine you’re using for container development and/or managing deployments of “big software” on remote servers. If you don’t have such a machine, we have a quick tutorial for building one.
To inject an SSH key into a remote server and set it up for passwordless login, you need a remote server or virtual machine running a Linux server distribution (in this tutorial, we’re using Ubuntu Server). If you don’t have such a server, we have a quick tutorial for building one of these, as well.
Step 1: Generate an SSH keypair on your development machine
Begin by creating an .ssh directory on your bootstrap machine, if this doesn’t already exist.
mkdir –p $HOME/.ssh
Change permissions on this directory:
sudo chmod 0700 $HOME/.ssh
Move into the .ssh directory and run the ssh-keygen utility to create a high-security keypair:
cd .ssh
ssh–keygen –t rsa 4096
This will create files called id_rsa (private key) and id_rsa.pub (public key). Then change the permissions on the private key:
sudo chmod 0600 id_rsa
Step 2: Copy the public key to your remote server
Setup steps complete, you can now copy your public key to your remote server on its IP address.
ssh-copy-id <user>@<ip_address>
The remote server will ask for your password before permitting the action to complete.
Thereafter, you should be able to ssh to this host without a password:
ssh -i ~/.ssh/id_rsa <user>@<ip_address>
Often, in such situations, the next step would be to disable SSH password access on the server, but this is probably unnecessary for servers running on a closed private network.