利用密钥来免密码登录

主机1:192.168.100.248 Linux主机
主机2:192.168.100.249 Linux主机
主机1 生成密钥(公钥和私钥),把公钥复制到主机2上

1.主机1生成密钥


[root@server3 ~]# ssh-keygen -b 1024 -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:
98:ab:82:16:c9:54:f5:41:6e:74:f9:e6:ea:5a:0e:82 root@server3.com

-b 1024 采用长度为1024字节的公钥/私钥对,最长4096字节,一般1024或2048就足够满足安全需要了,太长的话加密解密需要的时间也增长。
-t rsa  采用rsa加密方式的公钥/私钥对,除了rsa还有dsa方式,rsa方式最短不能小于768字节长度。
如果还需要使用更多其他参数请参考man ssh-keygen。
输入密码短句 Enter passphrase (empty for no passphrase) ,密码短句(passphrase)是你使用一个短语或者一句话作为密码输入,再由系统内部的加密或是散列算法生成虚拟密码后,进行下一步的认证。好处是增强了安全性不易被破解。

2.复制公钥到主机2上


[root@server3 ~]# scp /root/.ssh/id_rsa.pub root@192.168.100.249:/root
The authenticity of host '192.168.100.249 (192.168.100.249)' can't be established.
RSA key fingerprint is 91:a9:f9:6c:cd:6b:69:69:78:e0:f0:0f:a1:7f:c3:d8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.100.249' (RSA) to the list of known hosts.
root@192.168.100.249's password:
id_rsa.pub                                                                                                   100%  226     0.2KB/s   00:00   

3.主机2上


[root@server4 ~]# mkdir .ssh
[root@server4 ~]# cat id_rsa.pub >> .ssh/authorized_keys
[root@server4 ~]# chmod -R 600 .ssh
[root@server4 ~]# ll .ssh/authorized_keys
-rw------- 1 root root 226 07-19 23:54 .ssh/authorized_keys
[root@server4 ~]#

4.在主机1上测试登录主机2


[root@server3 ~]# ssh -lroot 192.168.100.249
Enter passphrase for key '/root/.ssh/id_rsa':             #输入密钥短语
Last login: Fri Jul 20 00:39:36 2012 from 192.168.100.248
[root@server4 ~]# 

标签:linux, ssh, 无密码, 密钥, 登录

添加新评论