Create and manage SSH keys for authentication to a Linux server

Say the hostname of the server is agnkiaa (e.g. set in your local /etc/hosts file), with its ip address being 162.***.***.***, we can set up SSH keys following the steps below.

Step 1: Generate keygen pair (client)

On the local client(客户端,例如笔记本电脑):

ssh-keygen -m PEM -t rsa -C "username@your_local_machine"

The string “username@your_local_machine” is added to make the string of the public key more recognizable on the server.


(base) ➜  ~ ssh-keygen -m PEM -t rsa -C "username@your_local_machine"
Generating public/private rsa key pair.
Enter file in which to save the key (~/.ssh/id_rsa): ~/.ssh/id_rsa_agn    
Enter passphrase (empty for no passphrase): [Can be different from the ssh passwd]
Enter same passphrase again: 
Your identification has been saved in ~/.ssh/id_rsa_agn
Your public key has been saved in ~/.ssh/
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx username@your_local_machine
The key\'s randomart image is:
+---[RSA 3072]----+
|    .............|
|   ..............|
|  ...............|
|   ..............|
|    .............|
|     .......     |
|        ...      |
|                 |
|                 |

Step 2: Upload your public key to the server

Make sure ssh-agent is running on your local machine.

eval "$(ssh-agent -s)"

Add your private key to ssh-agent.

ssh-add ~/.ssh/id_rsa_agn

From local client:

ssh-copy-id -i ~/.ssh/id_rsa_agn username@agnkiaa

Upload manually

From local client:

cat ~/.ssh/ | ssh username@agnkiaa "cat >> ~/.ssh/authorized_keys"

If ~/.ssh does not exist on the server, excute the following line:

cat ~/.ssh/ | ssh username@agnkiaa "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

Step 3: Configure SSH (local)

vim ~/.ssh/config

Locate the configuration of the agnkiaa server which may look like:

Host agnkiaa
  HostName agnkiaa
  User username ## Your own user name 


Host 162.***.***.***
  HostName 162.***.***.***
  User username

if you use ip as the host name.

Add a new line to the bottom of the configuration:

Host agnkiaa
  HostName agnkiaa
  User username
  IdentityFile ~/.ssh/id_rsa_agn

Then you can use ssh username@agnkiaa or VScode to connect to the server.