转:使用ssh公钥实现ssh免密码登录

http://hi.baidu.com/meloidea/blog/item/63779f222b39faf0d7cae205.html

原理:

密匙认证需要依靠密匙,首先创建一对密匙(包括公匙和密匙,并且用公匙加密的数据只能用密匙解密),并把公匙放到需要远程服务器上。这样当登录远程服务器时,客户端软件就会向服务器发出请求,请求用你的密匙进行认证。服务器收到请求之后,先在你在该服务器的宿主目录下寻找你的公匙,然后检查该公匙是否是合法,如果合法就用公匙加密一随机数(即所谓的challenge)并发送给客户端软件。客户端软件收到 “challenge”之后就用私匙解密再把它发送给服务器。因为用公匙加密的数据只能用密匙解密,服务器经过比较就可以知道该客户连接的合法性。

客户机:172.16.142.4
远端主机:172.16.142.5

在客户机以root用户执行下述命令:
[root@localhost .ssh]# /usr/bin/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:
30:f6:d7:2a:ac:56:eb:3f:fa:40:25:8d:90:96:68:cb [email protected]
------------------------------------------------
说明:
该命令将在用户的主目录/.ssh目录下面产生一对密钥
一般采用的ssh的rsa密钥:
id_rsa     私钥
id_rsa.pub 公钥
下述命令产生不同类型的密钥
ssh-keygen -t dsa
ssh-keygen -t rsa
ssh-keygen -t rsa1
-------------------------------------------------------
[root@localhost .ssh]# scp /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys

The authenticity of host '172.16.142.5 (172.16.142.5)' can't be established.
RSA key fingerprint is 4b:a5:74:fb:2e:08:60:af:fa:76:d4:b0:26:4c:13:75.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.142.5' (RSA) to the list of known hosts.
[email protected]'s password:

id_rsa.pub                                                                                        100% 236     0.2KB/s   00:00
-------------------------------------------------------------
说明:
将公钥拷贝到远端主机,并写入授权列表文件
你也可以把公钥文件拷贝过去后,在远端主机下直接执行
touch /root/.ssh/authorized_keys
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys

-------------------------------------------------------------

操作完毕,登陆检查。  
[root@localhost .ssh]# ssh 172.16.142.5
[email protected]'s password:

请注意此时如果仍提示输入密码,请检查如下文件夹和文件的操作权限,这是非常重要的, 否则ssh公钥认证体制不能正常工作:

172.16.142.4(客户端)
/home/root文件夹的权限是600
/home/root/.ssh文件夹的权限是600 (好像这个权限关系不是很大)
/home/root/.ssh/id_dsa私钥的权限600

172.16.142.5(远端主机)
/home/root文件夹的权限是644
/home/root/.ssh文件夹的权限是644 (好像这个权限关系不是很大)
/root/.ssh/authorized_keys公钥的权限644

--------------------------------------------------------------
[root@localhost ~]# ssh 172.16.142.5
Last login: Sat Dec 15 21:10:17 2007 from 172.16.142.4
[root@localhost ~]#
无密码SSH登陆成功!

 

你可能感兴趣的:(转:使用ssh公钥实现ssh免密码登录)