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

How to ssh to localhost without password?

1个答案

1

To connect to localhost via SSH without a password, configure SSH key-based authentication. Below are the detailed steps:

Step 1: Generate SSH Keys

First, generate a pair of SSH keys (a public key and a private key) on your machine. This can be done using the ssh-keygen command, which by default generates an RSA key pair.

bash
ssh-keygen -t rsa -b 4096

When prompted for the file save path, press Enter to accept the default path (typically ~/.ssh/id_rsa). If asked whether to enter a passphrase, press Enter to skip it for passwordless login.

Step 2: Add Public Key to Authorization File

Next, add the generated public key (located by default at ~/.ssh/id_rsa.pub) to the ~/.ssh/authorized_keys file for the same user. This can be done with the following command:

bash
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Ensure the permissions of the ~/.ssh/authorized_keys file are correct. Use the following command to set them:

bash
chmod 600 ~/.ssh/authorized_keys

Step 3: Verify SSH Server Configuration

Ensure your SSH server configuration (typically in the /etc/ssh/sshd_config file) allows key-based authentication. Locate the following lines and confirm they are set as shown:

plaintext
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys

If you make changes, restart the SSH service:

bash
sudo systemctl restart sshd

Step 4: Use SSH Keys for Login

Now you should be able to log in to localhost via SSH without a password. Test it with:

bash
ssh localhost

The system should not prompt for a password and log you in directly.

Example

I once needed to automate certain tasks in my development environment, including file transfers between servers. With the above setup, I was able to achieve passwordless SSH login in scripts, greatly simplifying the automation process.

This method is not only applicable to local environments but also to any remote server, provided you have permission to edit the ~/.ssh/authorized_keys file on the remote server. This setup is particularly useful for automated deployment and managing multiple servers.

2024年8月5日 10:07 回复

你的答案