对于机器A B C,实现相互ssh免密登录
生成各自的ssh秘钥
ssh-keygen -t rsa
一路回车,都是默认
秘钥会生成在~/.ssh
的id_rsa
和id_rsa.pub
中,将三台机器的~/.ssh/id_rsa.pub
汇总(放在一个文件里),可以用scp发送,也可以单纯复制粘贴到一起,将生成的总秘钥放在三台机器的~/.ssh/authorized_keys
中(新建)
修改文件权限
所有机器都进行修改,不然可能由于权限问题导致失败
chmod 0700 ~
chmod 0700 ~/.ssh
chmod 0600 ~/.ssh/authorized_keys
修改配置文件
修改/etc/ssh/sshd_config的内容,找到对应位置并修改
StrictModes no
PubkeyAuthentication yes
PasswordAuthentication yes
一切配好之后记得重启ssh服务systemctl restart sshd.service
遇到问题可以使用ssh -vvv ip
进行排查
备注:
如果将A机器的id_rsa.pub发送给B机器并保存,那么是A机器能免密登录B机器。我因为一开始搞混了,导致虽然发了秘钥,但还是需要密码才能登录,花了很长时间配置才发现。用ssh -vvv ip
排查时出现:
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/ /.ssh/id_rsa
debug3: no such identity: /home/ /.ssh/id_rsa: No such file or directory
debug1: Trying private key: /home/ /.ssh/id_dsa
debug3: no such identity: /home/ /.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/ /.ssh/id_ecdsa
debug3: no such identity: /home/ /.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/ /.ssh/id_ed25519
debug3: no such identity: /home/ /.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
其中发现说是找不到~/.ssh/id_rsa
,但是权限已经配好,当时是B机器拥有A机器的id_rsa.pub,我却用B机器尝试免密登陆A机器,B机器没生成秘钥也就没有~/.ssh/id_rsa
,搞混了。重新生成B机器秘钥并把id_rsa.pub发给A机器并保存就行了,或者直接点每个机器都拥有其他机器的秘钥就能相互登录了。