SSH免密登录

9

SSH免密登录

1、在客户端创建秘钥

ssh-keygen //一直回车即可

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:LhCYaJYje+wUpUtWC/B90v3gQtuahat5RbvkMqekqi4 root@lixianglin
The key's randomart image is:
+---[RSA 2048]----+
|... o            |
| o.O o .         |
|o=O = + o        |
|+=.o = =.o       |
|. = . +.S..      |
| +   . B+        |
|  .   *+..       |
|E    =+.+        |
|+o..+..=         |
+----[SHA256]-----+

会在~/.ssh目录生成两个文件文件

  • id_rsa (私钥)
  • id_rsa.pub (公钥)

2、将公钥复制到服务器上

ssh-copy-id -i ~/.ssh/id_rsa.pub root@x.x.x.x
也可以将id_rsa.pub 文件内容复制到~/.ssh/authorized_keys
[root@~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@x.x.x.x
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'x.x.x.x (x.x.x.x)' can't be established.
ECDSA key fingerprint is SHA256:NdgtW0QdHa6fhpoYATOhPDSKYrk5eNvxI5f01VpxZ7c.
ECDSA key fingerprint is MD5:8d:54:13:f6:89:e0:24:c4:fd:e8:1e:79:58:e3:f9:4e.
Are you sure you want to continue connecting (yes/no)? yes
/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
root@x.x.x.x's password: 

Number of key(s) added: 1

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

3、完成

可登录服务器查看文件

ssh root@x.x.x.x
cd ~/.ssh
vim authorized_keys