乐闻世界logo
搜索文章和话题

How do you set up SSH public key authentication between two Linux servers?

1个答案

1

1. Check SSH Service

First, verify that both servers have the SSH service installed. To check if the SSH service is running, use the following command:

bash
sudo systemctl status ssh

If the service is not running, start it with:

bash
sudo systemctl start ssh

2. Generate SSH Key Pair

On the source server, generate a new SSH key pair (a public key and a private key) using the ssh-keygen command. Run:

bash
ssh-keygen -t rsa -b 4096

When prompted for the file location, press Enter to accept the default (typically ~/.ssh/id_rsa). The system will ask if you want to set a passphrase; this is optional.

3. Copy Public Key to Target Server

Use the ssh-copy-id command to copy the public key to the ~/.ssh/authorized_keys file on the target server. Provide the username and IP address of the target server:

bash
ssh-copy-id username@target-server-ip

This command will prompt you for the target server's user password.

4. Test SSH Public-Key Authentication

Now, test the SSH public-key authentication by connecting to the target server using the following command:

bash
ssh username@target-server-ip

If configured correctly, you should be able to log in without entering a password.

5. (Optional) Enhanced Security Settings

To enhance security, edit the /etc/ssh/sshd_config file on both the source and target servers to ensure the following settings are enabled:

  • PasswordAuthentication no – Disable password authentication
  • PermitRootLogin no – Disable root login
  • PubkeyAuthentication yes – Enable public-key authentication

After making changes, do not forget to restart the SSH service to apply the changes:

bash
sudo systemctl restart ssh

Real-World Example

In my previous work, we frequently needed to automatically deploy code from the development server (DevServer) to the production server (ProdServer). By setting up SSH public-key authentication, our deployment scripts could securely connect to ProdServer from DevServer without manual intervention to perform necessary deployment tasks. This not only improved deployment efficiency but also enhanced system security.

2024年8月14日 13:19 回复

你的答案