Jannah Theme License is not validated, Go to the theme options page to validate the license, You need a single license for each domain name.
Linux

How to Generate SSH Keys on Ubuntu?

Introduction

SSH (Secure Shell) keys offer a reliable and secure way to authenticate connections to remote systems without needing traditional passwords. Unlike passwords, which are often vulnerable to brute-force attacks, SSH keys are cryptographic keys that provide an extra layer of security and are far more difficult to compromise. This makes SSH keys an ideal choice for developers, administrators, and anyone managing sensitive or high-access environments.

This guide covers all essential steps for generating and setting up SSH keys on an Ubuntu system. Starting with the creation of an SSH key pair, we’ll then go over methods for transferring your public key to a remote server, including automated and manual options. Additionally, we’ll cover how to set up a passwordless SSH login for even more streamlined access. By the end of this guide, you’ll have a fully configured SSH setup that enables secure, efficient, and password-free access to your Ubuntu server. Whether you’re new to SSH or simply need a refresher, these steps will simplify your setup and enhance your server’s security.

How to Generate and Set Up SSH Keys on Ubuntu

How to Generate and Set Up SSH Keys on Ubuntu

Generate SSH Key Pair

Open Terminal: On your local machine, locate and open the terminal application. If you’re using a graphical user interface, you can generally locate the terminal in your applications menu, or you may employ a keyboard shortcut (like Ctrl + Alt + T in many Linux distributions).

Generate Key Pair: In the terminal, enter the given below command to generate a new SSH key pair:

ssh-keygen -t rsa -b 4096
  • The -t rsa option mentions that you want to use the RSA algorithm for your keys. RSA is a widely used public-key cryptosystem known for its security and compatibility across various platforms and applications.
  • The -b 4096 option sets the key size to 4096 bits. A larger key size generally means stronger security, as it becomes increasingly difficult for attackers to crack the key via brute-force approaches. While 2048 bits is the minimum recommended size for security, using 4096 bits provides an additional layer of protection.

Specify Key Location: After entering the command, you will be asked to pick a site to save your new SSH key pair. By default, it will be saved in the ~/.ssh/ directory with the filename id_rsa for the private key and id_rsa.pub for the public key. If you press Enter without typing a different path, these defaults will be used. If you desire to employ a different name or location, you can mention it at this point. Just ensure you remember where you saved the keys for future use.

Add Passphrase (Optional): Next, you will possess the choice to append a passphrase to your private key. This step is your choice, but it is extremely suggested for intensifying protection. Adding a passphrase means that even if someone were to obtain your private key, they would also need the passphrase to use it. You will need to enter this passphrase each time you use the key, unless you add the key to an SSH agent, which allows it to remember your passphrase for you.

Once you complete these steps, you will have generated a public key (id_rsa.pub) and a private key (id_rsa) stored in the .ssh directory on your local machine. These keys form the basis of your secure SSH authentication, enabling encrypted connections to remote servers.

Copy Public Key to Ubuntu Server

Copy Public Key to Ubuntu Server

After creating the SSH key pair, the further essential step is to copy the public key to your Ubuntu server. This permits you to set secure, passwordless connections. There are several approaches to accomplish this, each with its distinct benefits.

Using ssh-copy-id Script

Run ssh-copy-id Command: The simplest and most efficient way to copy your public key to the server is by employing the ssh-copy-id command. This command automates the process, making it less error-prone. Input the given below command in your terminal:

ssh-copy-id username@server_ip

Replace username with your actual username on the server and server_ip with the server’s IP address. 

Authenticate: Upon running the command, you will be pinged to enter your password for the server. This step is significant, as it authenticates your recognition and renders access to the server. After successful authentication, the ssh-copy-id script automatically copies your public key to the server’s ~/.ssh/authorized_keys file. This allows your server to recognize your key and enables secure connections without the need for a password in the future.

Copy Public Key Manually

If the ssh-copy-id script is not available, you can still copy your public key manually. While this process requires a few more steps, it is equally effective.

Display Public Key Content: First, you need to view the your public key’s content. You can do this by entering the given below command in your terminal:

cat ~/.ssh/id_rsa.pub

This command will display your public key on the terminal screen.

Copy Output: Carefully select and copy the entire key content that is displayed. Make sure not to include any extra spaces or newlines, as this could cause issues when adding the key to the server.

Access Server and Create Key File: Next, you are required to log in to your server employing your existing authentication method (username & password). Once logged in, check if the ~/.ssh directory exists. If it doesn’t, create it by running:

mkdir -p ~/.ssh

Then, create or edit the authorized_keys file to append your public key. Use the following command:

echo "your-public-key" >> ~/.ssh/authorized_keys

Be sure to replace your-public-key with the actual public key you copied earlier.

Ensure Correct Permissions: Proper permissions are crucial for security. Set the appropriate permissions on the .ssh directory and the authorized_keys file using the following commands:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

This ensures that only your user has access to the SSH configuration files, which helps protect against unauthorized access.

Using Cat and SSH Together

Another efficient method for copying your public key involves combining the cat command with SSH. This approach allows you to transfer the key in one step, which can be particularly useful for users who prefer streamlined processes. Input the given below command in your local terminal:

cat ~/.ssh/id_rsa.pub | ssh username@server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

In this command, the cat ~/.ssh/id_rsa.pub part reads your public key, and the | (pipe) sends the output to the SSH command. The SSH command logs into your server and creates the ~/.ssh directory if it doesn’t already exist, then appends your public key to the authorized_keys file. This method is quick and avoids the need for manually copying and pasting the key content, making it a great choice for users looking to simplify the setup process.

After successfully copying your public key using any of these methods, you’ll be well on your way to securely accessing your Ubuntu server without needing to enter a password each time.

Log In to the Remote Server

Log In to the Remote Server

Once you have successfully copied your public key to the server, you can log in without needing to enter a password. This streamlined method enhances security and simplifies your workflow, especially if you frequently access the server.

To log in, use the SSH command in your terminal:

ssh username@server_ip

Replace username with your actual username on the server and server_ip with the IP address of a server. This command initiates an SSH connection to the remote server using your public key for authentication.

What Happens Next:

  1. Connection Establishment: When you run the SSH command, your local machine attempts to establish a connection to the specified server. The SSH client on your machine sends a request to the server, and if the public key you copied earlier matches the private key on your local machine, the server grants access.
  2. Authentication Process: The server checks its ~/.ssh/authorized_keys file for your public key. If it finds a matching key, it verifies your recognition without needing a password. If everything is set up aptly, you must be granted access to the server directly.
  3. Successful Login: If the connection is successful, your terminal will change to indicate that you are now logged into the remote server. You will typically see a welcome message that may include system information or a reminder of your last login time.
  4. Session Management: Once logged in, you can execute commands on the remote server just as you would on your local machine. You can navigate directories, manage files, run scripts, and perform administrative tasks without interruptions from password prompts.

Set up Passwordless SSH Login (Optional)

Set up Passwordless SSH Login (Optional)

To enhance the convenience of your SSH sessions, you can configure your system to remember your private key in memory. This setup enables you to log in to your remote server without requiring to enter your passphrase every time. This can considerably streamline your workflow, specifically if you regularly connect to multiple servers.

Step 1: Start the SSH Agent

Before adding your private key, you need to start the SSH agent. The SSH agent is a background program that administers your SSH keys and manages your passphrase. To initiate the agent, run the given below command in your terminal:

eval "$(ssh-agent -s)"

This command starts the SSH agent and sets the appropriate platform variables for your session. You must see a confirmation message showing the agent’s process ID, indicating that it’s running successfully.

Step 2: Add Your SSH Key to the Agent

As soon as the SSH agent is running, you add your private key to the agent. This allows the agent to keep your key in memory for the span of your session. Employ the given below command to add your key:

ssh-add ~/.ssh/id_rsa

If you saved your private key with a different name or location, ensure you adjust the path accordingly. After running this command, you will be pinged to input the passphrase for your private key one last time. Once entered, the agent will hold your key in memory.

Optional: Configure SSH Agent to Start Automatically

For an even smoother experience, you can configure your SSH agent to start automatically when you log in. If you’re using a Linux distribution with a graphical interface, you can often find options in your desktop environment’s settings to manage startup applications. Here’s a general approach:

1. Edit Your Shell Configuration: Open your shell configuration file (like ~/.bashrc, ~/.bash_profile, or ~/.zshrc) in a text editor.

2. Add the SSH Agent Command: Append the following lines to the end of the file to ensure the SSH agent starts automatically upon login:

# Start SSH Agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

3. Reload Your Configuration: After saving the changes, reload your shell configuration to apply the changes:

source ~/.bashrc  # or the respective file you edited

Also Read: How to Transfer Files with Rsync over SSH

Conclusion

Using SSH keys on Ubuntu isn’t just about security; it’s also about improving the efficiency of your workflow. With an SSH key pair, you gain a powerful, secure method of connecting to remote servers without needing to remember or input passwords. This is especially beneficial for those who frequently access multiple servers, as it minimizes the hassle of repeated logins and mitigates risks associated with password management.

By following the steps in this guide—from generating your SSH key pair and transferring the public key to configuring passwordless login—you’ve created a secure and resilient method of connecting to your Ubuntu server. This setup is ideal for ongoing tasks like development, deployment, or routine server maintenance, where security and ease of access are essential. With SSH key authentication, you’re leveraging a robust security measure that’s widely adopted in the industry, improving both your personal productivity and the overall protection of your systems.

Arpit Saini

He is the Director of Cloud Operations at Serverwala and also follows a passion to break complex tech topics into practical and easy-to-understand articles. He loves to write about Web Hosting, Software, Virtualization, Cloud Computing, and much more.

Related Articles