生成密钥对

宿主机任意下目录执行:

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): host2servera_id_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in host2servera_id_rsa.
Your public key has been saved in host2servera_id_rsa.pub.
The key fingerprint is:
SHA256:OkWcw+R3x6Z2mzeYQuG033H3N9qIeym3TZKzz6YD8tQ user@ubuntu18
The key's randomart image is:
+---[RSA 2048]----+
|        .        |
|       = .   .   |
|        B .o. +  |
|       . oo.o+   |
|        S  ++ ..o|
|       o ..+.A=o=|
|      o   +..B+=+|
|       .   oo=@o+|
|           o=ss= |
+----[SHA256]-----+

一直回车确定,生成公私钥,保存在~/.ssh目录下。

我在宿主机上生成的公私钥名称为,分别是host2servera_id_rsa,host2servera_id_rsa.pub方便我记忆。如果一直回车,那么生成的公私钥名称为id_rsaid_rsa.pub

发送公钥

将公钥复制到服务器 ServerA 上,以 IP:10.12.193.53 为例。

$ ssh-copy-id 10.12.193.53
# 输入密码
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
user@10.12.193.53's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.12.193.53'"
and check to make sure that only the key(s) you wanted were added.

默认是把 ServerA 的用户当做 user 进行登录。如果有确定的用户如userA,就使用ssh-copy-id userA@10.12.193.53

然后就可以直接免密码登录了:

ssh user@10.12.193.53
# 或者
ssh userA@10.12.193.53

如果还是需要输入密码,可能ssh-agent没有启动,执行eval $(ssh-agent)启动ssh-agent,然后再次登录即可。然后将私钥添加到ssh-agent中,执行ssh-add ~/.ssh/host2servera_id_rsa,然后再次登录即可。

配置快捷登录

即使免密登录,输入一长串 IP 也太麻烦了,能不能配置更简单的登录方式,比如给服务器起个名字如ServerA直接使用ssh ServerA就登录服务器,能。

打开~/.ssh/config配置如下内容:

Host ServerA
    HostName 10.12.193.53
    Port 22
    User userA
    IdentityFile ~/.ssh/host2servera_id_rsa

然后就可以直接使用ssh ServerA登录了。