Linux 环境下配置 SSH 免密登录与互信详解
场景说明
假设我们有两个节点:
- 主机 A:10.0.5.199
- 主机 B:10.0.5.198 目标是让主机 A 能够免密登录到自身及主机 B。
前置准备
确保所有主机的防火墙已关闭,避免端口拦截。
生成密钥对
在主机 A 上操作,进入 .ssh 目录并生成 RSA 密钥:
cd ~/.ssh
ssh-keygen -t rsa
一路回车即可,默认会将私钥保存在 id_rsa,公钥在 id_rsa.pub。
分发公钥
将生成的公钥复制为 authorized_keys 文件,这样本机就能免密登录了:
cp id_rsa.pub authorized_keys
此时尝试 ssh localhost,应该无需输入密码。
接下来把这份授权文件发给主机 B。可以使用 scp 传输,或者更推荐直接用 ssh-copy-id 工具(如果系统支持):
scp authorized_keys [email protected]:~/.ssh/
chmod 600 ~/.ssh/authorized_keys
注意权限设置,SSH 对权限非常敏感,authorized_keys 必须是 600,.ssh 目录必须是 700。
常见问题排查
配置完成后若仍提示需要密码,或出现报错,可参考以下方案:
-
Agent 签名失败 如果出现
Agent admitted failure to sign using the key,说明私钥未加载到代理中:ssh-add强制将私钥加入代理缓存。
-
权限问题导致无法免密 如果没有报错但依然要输密码,检查被连接主机(如主机 B)上的权限:
chmod o-w ~/ chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys -
SSH Agent 状态异常 检查代理进程是否存活:
ps -Af | grep agent如果有残留进程,先 kill 掉再重启;或者直接执行
ssh-agent开启新会话。若仍不行,尝试重启 SSH 服务:sudo service sshd restart -
连接认证代理失败 执行
ssh-add时报错Could not open a connection to your authentication agent,可以尝试指定 shell 启动代理:ssh-agent bash

