使用秘钥远程登录

使用Linux远程登录其他主机时总是要输入密码?
用秘钥登录可免去输入密码的过程

1. 非对称加密原理
分享一个链接:图解公钥与私钥,讲解很生动。

2. 一句话概括秘钥远程登录的配置

Clent产生密钥对,将Client的公钥写入Server的 /root/.ssh/authorized_keys 文件中即可

3. Linux操作步骤

a. Client上创建密钥对(一路回车即可)
命令:ssh-keygen -t rsa ##其实不加-t rsa也可,默认就是用rsa加密算法的

[root@choco-02 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
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:Ohww3/rX2kOTGcbnwVz9IiGrSMb8saqtK9Fg4lwdeoE root@choco-02
The key's randomart image is:
+---[RSA 2048]----+
|    .           .|
|   E o    . .   o|
|    =oo    + + ..|
|. oo *=.. . = * .|
|oo.o.oooS+ . B o |
| o. ...++   = .  |
|   .  =.   o .   |
|  .  ..o  ..o    |
|   .++. ......   |
+----[SHA256]-----+
[root@choco-02 ~]# ls .ssh/
id_rsa  id_rsa.pub           

最终在 /root/.ssh下生成密钥对,id_rsa为私钥,id_rsa.pub为公钥

b. 将公钥内容传递到Server的 /root/.ssh/authorized_keys 文件内(方法较多)

前提:在Server的 /root/ 目录下,有权限为 700.ssh 目录;在 .ssh 目录中有权限为 600authorized_keys 文件。但如果使用下述第二种方式则会自动建立以上目录及文件。

第一种:在Xshell中复制Client的公钥内容,粘贴进Server的authorized_keys中。

第二种:使用ssh-copy-id命令
命令:ssh-copy-id -i @

  • 在Client上传输公钥至Server
[root@choco-02 .ssh]# ssh-copy-id -i id_rsa.pub [email protected]
/usr/bin/ssh- copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any 
/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
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added
[root@choco-02 .ssh]# 
  • 此时在Server的/root/.ssh/authorized_keys中已存在Client的公钥
[root@choco-01 ~]# cat .ssh/authorized_keys 
ssh-rsa A.................此处省略.........7L root@choco-02
  • Client已可以使用密钥登陆Server
[root@choco-02 .ssh]# ssh [email protected]
Last login: Thu May 10 11:44:13 2018 from 192.168.1.1
[root@choco-01 ~]# 

第三种:用scp传输公钥,并用 cat .... >> /root/.ssh/authorized_keys的方式将Client公钥追加至该文件尾部。

Tips. 加入authorized_keys文件的公钥,最好注释出是哪台Client的公钥

你可能感兴趣的:(使用秘钥远程登录)