Passwordless login is primarily based on the SSH (Secure Shell) protocol, utilizing key pairs for authentication. In simple terms, a pair of keys, including a public key and a private key, is generated on the client side (the server initiating the login). The public key is then added to the authorized list on the server side (the server being logged into). When the client attempts to log into the server, it sends its public key. The server, upon receiving it, encrypts a random piece of data using the public key and sends the encrypted data back to the client. The client receives the encrypted data, decrypts it using its private key, and sends the decrypted result back to the server. The server compares the decrypted result with the original data; if they match, the client is authenticated, allowing for passwordless login. Although it sounds a bit complex, it is not difficult to operate. Just follow me step by step!
(1) Environment Preparation
We assume there are two Linux servers, one acting as the client (Server A) and the other as the server (Server B). To ensure smooth operation, make sure both servers have SSH service installed and can connect to the network. You can check the SSH service status by entering the following command in the terminal:
sudo systemctl status ssh
(2) Generate Key Pair on the Client (Server A)
In the terminal of Server A, enter the following command to generate a key pair:
ssh-keygen -t rsa
After executing the command, a series of prompts will appear:
First, it will ask you where to save the key. Simply press the Enter key to use the default path (usually ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub).
Next, it will prompt you to enter a passphrase. It is recommended to just press the Enter key without setting a passphrase (while setting a passphrase is more secure, it would require entering it every time you log in, defeating the purpose of passwordless login).
Finally, the fingerprint information of the key pair will be displayed. Once confirmed, the key pair is successfully generated.
(3) Add the Client’s Public Key to the Server (Server B)
Use the following command to copy Server A’s public key to Server B:
ssh-copy-id username@ServerB_IP
After executing the command, you will be prompted to enter the password for Server B. Once the correct password is entered, the public key will be automatically added to Server B’s ~/.ssh/authorized_keys file.
(4) Test Passwordless Login
In the terminal of Server A, enter the following command to attempt to log into Server B:
ssh username@ServerB_IP
If everything goes smoothly, you will log into Server B without needing to enter a password. Isn’t that super convenient!