为了方便管理,在需要频繁登陆机器,特别是在机器众多的时候,免密码登录系统就显得很需要了。
建立信任关系其实很简单……
模拟情况,A机器想要免密码用ssh登录B机器:
进行一下几步操作就可以完成免密码登陆了:
1、生成A机器的公私钥匙对,英文原文是这样的:Generating public/private rsa key pair.
用这条命令生成:ssh-keygen -b 1024 -t rsa
-b 选项是生成rsa钥匙对的位数,man手册中是这样描述的:
- Specifies the number of bits in the key to create. For RSA keys, the minimum size is 768 bits and the
- default is 2048 bits. Generally, 2048 bits is considered sufficient. DSA keys must be exactly 1024
- bits as specified by FIPS 186-2.
说远一点,SSH的密钥选择不止有rsa,还有dsa,还有其他……
这里推荐使用dsa,因为ssh-keygen在生成 DSA 密钥时,其长度只能为1024位(基于NIST FIPS 186-2);而 ssh-keygen 在 RSA 的密钥长度上没有限制。
(由于小于1024位密钥长度的 RSA 已经有被攻破的记录,所以RSA 2048 位密钥是更好的选择,也就是 -b 2048)
命令执行结果如下
- [root@localhost ~]# 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:
- 40:44:8d:2c:20:bd:c0:1b:b2:01:9f:e8:f9:bb:db:67 root@localhost.localdomain
可以看到公钥和私钥都生成在了.shh目录下,公钥为id_rsa.pub,私钥为id_rsa
2、拷贝A机器的公钥到B机器的.shh目录,加入到authorized_keys文件中
用这个命令:scp .ssh/id_rsa.pub root@B机器IP:/root/.ssh/
完成拷贝
3、登录B机器,追加A机器的公钥到B机器的认证文件中:
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
OK,这个A机器到B机器的信任关系就建立好了。
你可以在A机器用SSH命令直接登录到B机器了。。。。。
--------------------------------------------------------------------------------------
另外一种拷贝公钥的方法,在生成好密钥对之后,使用下面这个命令:
1.[root@localhost ~]#ssh-copy-id -i id_rsa.pub root@machineB
-i 参数后面需要的是刚刚生成的id_rsa.pub公钥, ssh-copy-id 脚本会自动把id_rsa.pub里的内容追加到需要登录服务器的用户目录下,比如本例中的(/root/.ssh/authorized_keys中)
执行玩这条命令,即完成了信任关系的建立。