集群节点间免密登陆

原理

SSH 认证方式

SSH 支持两种主要认证方式:

  1. 密码认证:每次输入密码(默认方式)
  2. 密钥认证:使用公钥-私钥对(免密方式)

密钥认证工作流程

客户端                              服务端
--------                            --------
1. 生成密钥对
   - 私钥: id_rsa (保密)
   - 公钥: id_rsa.pub (可公开)

2. 将公钥复制到服务端
   → ~/.ssh/authorized_keys

3. 发起连接请求
   |
   |------ "我要登录" ------>
   |                          4. 生成随机挑战
   |<----- 加密挑战 --------
   |                          (用你的公钥加密)
   
4. 用私钥解密挑战
   计算响应
   |
   |------ 发送响应 -------->
   |                          6. 验证响应
   |                          如果正确 → 允许登录
   |<----- 登录成功 --------

关键点

配置步骤

场景1:共享 Home 目录(HPC 集群常见)

如果所有节点挂载同一个 home 目录(如 /gpfs/hpc/home/),配置极简:

# 1. 生成密钥对(如果没有)
ssh-keygen -t rsa -b 4096
# 一路回车,不设置密码

# 2. 将公钥添加到授权列表
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

# 3. 设置正确权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_rsa

# 完成!所有节点自动生效

原理:因为 home 目录共享,所有节点读取的是同一个 ~/.ssh/authorized_keys 文件。

场景2:独立 Home 目录

每个节点有独立的 home 目录时:

# 1. 在当前节点生成密钥对
ssh-keygen -t rsa -b 4096

# 2. 复制公钥到其他节点
ssh-copy-id user@node2
ssh-copy-id user@node3

# 或手动复制
cat ~/.ssh/id_rsa.pub | ssh node2 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

# 3. 如果需要双向免密,在每个节点重复上述步骤

文件说明

~/.ssh/
├── id_rsa              # 私钥(绝对保密,权限必须 600)
├── id_rsa.pub          # 公钥(可公开,对应的身份标识)
├── authorized_keys     # 授权公钥列表(权限必须 600)
├── known_hosts         # 已知主机指纹
└── config              # SSH 客户端配置(可选)

权限要求(非常重要)

# 目录权限
chmod 700 ~/.ssh          # 只有所有者可读写执行

# 文件权限
chmod 600 ~/.ssh/id_rsa           # 私钥:只有所有者可读写
chmod 644 ~/.ssh/id_rsa.pub       # 公钥:所有者读写,其他人只读
chmod 600 ~/.ssh/authorized_keys  # 授权列表:只有所有者可读写

权限错误会导致 SSH 拒绝使用密钥认证!

验证与调试

测试免密登录

ssh node2
# 应该直接登录,不需要密码

查看详细日志

ssh -v node2
# 或更详细
ssh -vvv node2

常见错误信息

错误 原因 解决方法
Permission denied (publickey) 公钥未添加或权限错误 检查 authorized_keys 和权限
Bad owner or permissions ~/.ssh 或密钥文件权限过宽 执行 chmod 命令修正权限
Connection refused SSH 服务未运行或端口错误 检查 sshd 状态

服务端排查

# 查看 SSH 服务日志
sudo tail -f /var/log/auth.log        # Debian/Ubuntu
sudo tail -f /var/log/secure           # RHEL/CentOS

# 检查 SSH 配置
sudo grep -E "PubkeyAuthentication|PasswordAuthentication" /etc/ssh/sshd_config
# 应该看到:
# PubkeyAuthentication yes

安全建议

  1. 不要设置私钥密码为空(在不可信环境)

    • 集群内部可以为空方便使用
    • 如果是外网服务器,建议设置密码保护
  2. 定期轮换密钥

    • 每 1-2 年重新生成一次
  3. 不要共享私钥

    • 每个用户/机器应该有自己的密钥对
  4. 限制登录来源(可选)

   # 在 ~/.ssh/authorized_keys 中指定来源 IP
   from="192.168.1.*" ssh-rsa AAAAB3...

高级技巧

SSH Config 简化登录

创建 ~/.ssh/config

Host node2
    HostName compute-node-02
    User guoyingwei
    IdentityFile ~/.ssh/id_rsa

Host node3
    HostName compute-node-03
    User guoyingwei
    IdentityFile ~/.ssh/id_rsa

之后只需 ssh node2 即可。

使用 SSH Agent(管理多个密钥)

# 启动 agent
eval $(ssh-agent)

# 添加密钥
ssh-add ~/.ssh/id_rsa

# 查看已添加的密钥
ssh-add -l