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:
bashsudo systemctl status ssh
If the service is not running, start it with:
bashsudo 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:
bashssh-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:
bashssh-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:
bashssh 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 authenticationPermitRootLogin no– Disable root loginPubkeyAuthentication yes– Enable public-key authentication
After making changes, do not forget to restart the SSH service to apply the changes:
bashsudo 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.