SSH Connection with Public/Private Keys | Linux
Secure Shell (SSH) is a secure protocol commonly used to establish secure connections between local and remote Linux systems, allowing users to execute commands on remote hosts, transfer files, or create secure tunnels. In this article, we will explore an important SSH feature - connecting to remote hosts using public/private key pairs.
Standard SSH Username/Password Connection
On a Linux system, if you are connecting to a remote host for the first time, you will most likely use a username and password to connect. The command is:
ssh user@remote_host
The first time, you may see:
The authenticity of host 'x.x.x.x (x.x.x.x)' can't be established.
ED25519 key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])?
After typing yes, you will see:
Warning: Permanently added 'x.x.x.x' to the list of known hosts.
Connection closed by x.x.x.x port 22
Then you enter the password, and the connection is established successfully.
Using Public/Private Key Pairs to Connect to Remote Linux Hosts
In practice, you may manage multiple Linux hosts, and each host can have multiple username/password combinations.
Therefore, we usually use public/private key pairs for SSH connections.
Note: Please keep the generated key pair secure. If there is any concern about leakage, replace it with a new key pair. For security purposes, key pairs should also be rotated regularly.
Generating an SSH Key Pair
First, we need to generate a key pair. This can be done with the following command: This command generates an RSA type key pair with a key length of 2048 bits. The generated key pair consists of a private key (typically saved at ~/.ssh/id_rsa) and a corresponding public key (saved at ~/.ssh/id_rsa.pub).
ssh-keygen -t rsa -b 2048
Copying the Public Key to the Remote Host
Before we can use the key pair for SSH connections, we need to copy the locally generated public key to the remote host. This can be done using the ssh-copy-id command or by manually adding the public key content to the ~/.ssh/authorized_keys file on the remote host.
ssh-copy-id user@remote_host
Secure SSH Connection
The -i option in this command specifies the path to the private key file, user is the username on the remote host, and remote_host is the IP address or hostname of the remote host. Once the key pair has been generated and configured, we can use the private key to establish a secure SSH connection to the remote host with the following command:
ssh -i ~/.ssh/id_rsa user@remote_host
Benefits of SSH Connection with Public/Private Keys
SSH public/private key pairs provide a more secure and convenient connection method, eliminating the need for passwords. This is an important step in securing data transmission while also improving connection convenience. Hope this article has been helpful to you!