Linux配置SSH免密登录

来自CloudWiki
跳转至: 导航搜索

基本原理

ssh 无密码登录要使用公钥与私钥。linux下可以用用ssh-keygen生成公钥/私钥对,

登录的机子要有私钥,被登录的机子要有登录机子的公钥。登陆机凭借这个公钥/私钥对访问被登陆的机子,这个公钥/私钥对一般在私钥宿主机产生。下面我以CentOS为例。

有机器A(192.168.1.155),B(192.168.1.181)。现想A通过ssh免密码登录到B机的git账户。

首先以git账户账户登陆为例。(也可以登陆到B机的其他账户)

操作步骤

生成公钥/私钥对

在A机下生成公钥/私钥对。

[root@A ~]# ssh-keygen -t rsa -P -C "maxin5452@163.com"


Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
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:1tnaQtZJLx8CQhuIDcEU9KxfzCYd5Cy2QSAPA1CdkLU root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|+o*OOO..+        |
|  .===o= o       |
|    E * * . .    |
|     o B + * o   |
|    . o S = * o  |
|     . = o o + . |
|      .   o . .  |
|           .     |
|                 |
+----[SHA256]-----+


-P表示密码,-P 就表示空密码,也可以不用-P参数,这样就要三车回车,用-P就一次回车。

该命令将在/root/.ssh目录下面产生一对密钥id_rsa和id_rsa.pub。

[root@localhost ~]# ls /root/.ssh

id_rsa  id_rsa.pub  known_hosts


一般采用的ssh的rsa密钥:

id_rsa     私钥
id_rsa.pub 公钥

下述命令产生不同类型的密钥

ssh-keygen -t dsa
ssh-keygen -t rsa
ssh-keygen -t rsa1

复制公钥文件

把A机下的/root/.ssh/id_rsa.pub 复制到B机的 /home/git/.ssh/authorized_keys文件里,

先要在B机上创建好 /root/.ssh 这个目录,用scp复制。

[git@Broot]$ mkdir /home/git/.ssh

[root@A ~]# scp /root/.ssh/id_rsa.pub root@10.0.0.30:/home/git/.ssh/authorized_keys

root@10.0.0.30's password:
id_rsa.pub                                    100%  408    49.5KB/s   00:00

由于还没有免密码登录的,所以要输入一次B机的root密码。

修改文件权限

authorized_keys的权限要是600!!!

[root@localhost ~]# ls -l /home/git/.ssh/authorized_keys

-rw-------. 1 git git 408 May 12 10:34 /home/git/.ssh/authorized_keys

[root@B~]# chmod 600 ~/.ssh

[root@B ~]# chmod 600 /home/git/.ssh/authorized_keys

要保证.ssh和authorized_keys都只有用户自己有写权限。否则验证无效。(今天就是遇到这个问题,找了好久问题所在),其实仔细想想,这样做是为了不会出现系统漏洞。


A机登录B机

[root@A ~]# ssh -l git 10.0.0.30

The authenticity of host '10.0.0.30 (10.0.0.30)' can't be established.
RSA key fingerprint is 00:a6:a8:87:eb:c7:40:10:39:cc:a0:eb:50:d9:6a:5b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.30' (RSA) to the list of known hosts.
Last login: Thu Jul  3 09:53:18 2008 from root
[git@B ~]#


第一次登录是时要你输入yes。

现在A机可以无密码登录B机的git账户了。

小结:登录的机子可有私钥,被登录的机子要有登录机子的公钥。这个公钥/私钥对一般在私钥宿主机产生。上面是用rsa算法的公钥/私钥对,当然也可以用dsa(对应的文件是id_dsa,id_dsa.pub)

想让A,B机无密码互登录,那B机以上面同样的方式配置即可。


参考文档:https://www.cnblogs.com/Percy_Lee/p/5698603.html