SSH Public Key Authentication

📢 This article was translated by gemini-3-flash-preview

Introduction

Typing a password every time I connect to a machine is a hassle (mostly because I keep forgetting it).

One-Click Setup

If your computer doesn’t have a public key yet, you need to generate one. It’s usually located at ~/.ssh/id_rsa.pub.

1
ssh-keygen

Then, run the following command on your local machine:

1
ssh-copy-id username@RemoteIP

Replace username with the account you want to log into, and RemoteIP with the target IP address.

Enter the password when prompted.

Now, you can log in directly via SSH:

1
ssh username@RemoteIP

Super convenient!

Manual Method (Writing to File)

Use this method if you need to add someone else’s public key or if you are locked out.

Edit the configuration file ~/.ssh/authorized_keys (you might need to adjust file permissions first). Add the public key, one per line, and save. (If you changed permissions, don’t forget to set them back to 600).

Actually, passwordless login should work at this point, but you might need to check the server configuration.

Edit /etc/ssh/sshd_config:

1
2
3
PasswordAuthentication yes      # Password authentication
RSAAuthentication yes         # RSA authentication
PubkeyAuthentication yes       # Public key authentication

If you want to require both a public key and a password for login:

Update the configuration file:

1
AuthenticationMethods publickey,password

Restart the SSHD service:

1
sudo service sshd restart

References

SSH 公钥登录 - starnight_cyber - 博客园

This post is licensed under CC BY-NC-SA 4.0 by the author.