Login via SSH key only

1. Create an SSH Key Pair

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

2. Copy the public key to the server

ssh-copy-id <username>@<server_ip>

If you have more than one key (identity), you can specify the key to use with the -i flag. (The default is ~/. ssh/id_rsa.pub)

You can also add the public key to the server manually. (This is useful if you don't have ssh-copy-id installed)

cat ~/.ssh/id_rsa.pub | ssh <username>@<server_ip> "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

or just copy the contents of the public key .pub and paste it in the ~/.ssh/authorized_keys file on the server.

ssh-copy-id -i ~/.ssh/id_rsa.pub <username>@<server_ip>

3. Test configuration

ssh <username>@<server_ip>
# If you are using a different key, you need to specify it with the -i flag.
ssh -i ~/.ssh/<key_name> <username>@<server_ip>

4. Disable SSH password login 

sudo nano /etc/ssh/sshd_config

Now search in file or add the line

PasswordAuthentication no

5. Restart SSH service

sudo systemctl restart ssh

© 2024 PappZ. All rights reserved.