SSH免密码登录

如果想SSH免密码登录一台机器,只需要如下两部就行:

1.生成公钥文件

首先需要说明的是,如果A想免密码登录B,那么只需要A在自己的机器上生成公钥文件发送到B对应的目录下面就可以,不要以为是把B的公钥发送到A,然后A就可以免密码登录了。

(1)生成密钥文件之前的目录

[root@centos003 .ssh]# ls
authorized_keys  known_hosts

(2)生成密钥

[root@centos003 .ssh]# ssh-keygen -t rsa
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:2oH8zHOnz8xRunYWZ3MHvxIDFTKq19lQODJaqnK0jCI root@centos003
The key's randomart image is:
+---[RSA 2048]----+
|           o.o.  |
|         +.o+.   |
|        +.o.o    |
|     o +. ..+ .  |
|    + =.S. o...o |
|E. o = *..   =..*|
|. . o . * . + o+=|
|         o *.+o. |
|          .o*o.  |
+----[SHA256]-----+

(3)生成密钥之后的目录结构

[root@centos003 .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts

文件功能解释:

  • authorized_keys:存放远程免密登录的公钥,主要通过这个文件记录多台机器的公钥
  • id_rsa : 生成的私钥文件
  • id_rsa.pub : 生成的公钥文件
  • know_hosts : 已知的主机公钥清单

如果希望ssh公钥生效需满足至少下面两个条件:

  • .ssh目录的权限必须是700 
  • .ssh/authorized_keys文件权限必须是600

2.发送密钥文件

(1)通过scp将内容写道对方的文件中

[root@centos004 .ssh]# scp -p ~/.ssh/id_rsa.pub root@129.204.16.68:/root/.ssh/authorized_keys
root@129.204.16.68's password: 
Permission denied, please try again.
root@129.204.16.68's password: 
id_rsa.pub                                                100%  396    12.8KB/s   00:00    
[root@centos004 .ssh]# ssh 129.204.16.68
Last failed login: Fri Dec 21 23:15:28 CST 2018 from 129.28.86.57 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Fri Dec 21 23:12:14 2018 from 113.90.236.210
[root@centos003 ~]# exit
logout
Connection to 129.204.16.68 closed.

(2)通过ssh-copy-id的方式

[root@centos003 .ssh]#  ssh-copy-id -i ~/.ssh/id_rsa.pub 129.28.86.57
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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@129.28.86.57's password: 
Permission denied, please try again.
root@129.28.86.57's password: 

Number of key(s) added: 1

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

[root@centos003 .ssh]# ssh 129.28.86.57
Last login: Fri Dec 21 23:16:15 2018 from 129.204.16.68
[root@centos004 ~]# exit
logout
Connection to 129.28.86.57 closed.

其实这个过程也可以分为两部,发送到目标服务器并追加到目标文件。

原文地址:https://www.cnblogs.com/yangmingxianshen/p/10159539.html