Step-by-Step Guide- Adding Your SSH Public Key to the Authorized_keys File for Secure Remote Access

by liuqiyue

How to Add SSH Public Key to authorized_keys

Adding your SSH public key to the authorized_keys file is a crucial step in setting up secure remote access to your server. This process allows you to authenticate yourself using your public key without the need for a password. In this article, we will guide you through the steps to add your SSH public key to the authorized_keys file on a Linux server.

Step 1: Generate SSH Key Pair

Before you can add your SSH public key to the authorized_keys file, you need to generate an SSH key pair. You can do this using the `ssh-keygen` command. Run the following command in your terminal:

“`
ssh-keygen -t rsa -b 4096
“`

This command will generate a new RSA key pair with a 4096-bit key size. You will be prompted to enter a file path for your private key and a passphrase for added security. Press Enter to accept the default file path and enter a passphrase if desired.

Step 2: Copy Your Public Key to the Server

Once you have generated your SSH key pair, you need to copy your public key to the server. You can do this by using the `ssh-copy-id` command. Run the following command in your terminal:

“`
ssh-copy-id -i ~/.ssh/id_rsa.pub username@server_ip
“`

Replace `username` with your server’s username and `server_ip` with the server’s IP address. You will be prompted to enter your password to authenticate the copy process.

Step 3: Add Your Public Key to the authorized_keys File

After copying your public key to the server, you need to add it to the authorized_keys file. The authorized_keys file is located in the user’s home directory under the `.ssh` folder. Run the following command to edit the authorized_keys file:

“`
nano ~/.ssh/authorized_keys
“`

If the authorized_keys file does not exist, the `nano` editor will create it for you. Paste your public key into the file, making sure to remove any existing keys if you want to replace them. Save and close the file by pressing Ctrl+X, then Y, and Enter.

Step 4: Set Proper Permissions

To ensure that your SSH key is secure, you need to set the correct permissions on the `.ssh` directory and the authorized_keys file. Run the following commands in your terminal:

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

These commands set the permissions so that only the user can read and write to the `.ssh` directory and the authorized_keys file.

Step 5: Test SSH Access

Finally, test your SSH connection by running the following command in your terminal:

“`
ssh username@server_ip
“`

If everything is set up correctly, you should be able to log in without being prompted for a password.

By following these steps, you can successfully add your SSH public key to the authorized_keys file on a Linux server. This will allow you to securely access your server using SSH key-based authentication.

You may also like