Linux 多机免密互信终极指南:IP、主机名与密钥分发全解析

1. 环境准备

假设三台机器信息如下:

主机名 IP地址 用户名
node1 192.168.1.1 user
node2 192.168.1.2 user
node3 192.168.1.3 user

2. 配置步骤

① 配置主机名解析(所有机器)

编辑每台机器的 /etc/hosts 文件,添加所有节点的 IP 和主机名映射:

sudo tee -a /etc/hosts <<EOF
192.168.1.1 node1
192.168.1.2 node2
192.168.1.3 node3
EOF

验证解析是否生效:

ping -c 2 node1  # 应能解析到 192.168.1.1

② 生成 SSH 密钥对(所有机器)

每台机器上执行:

ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""  # 免交互生成密钥
  • 生成的密钥文件:
    • 公钥:~/.ssh/id_rsa.pub
    • 私钥:~/.ssh/id_rsa(需保密)

③ 合并公钥到 authorized_keys

方法一:手动合并(推荐少量机器)

  1. node1 上收集所有公钥:

    cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
    ssh user@node2 "cat ~/.ssh/id_rsa.pub" >> ~/.ssh/authorized_keys
    ssh user@node3 "cat ~/.ssh/id_rsa.pub" >> ~/.ssh/authorized_keys
    
  2. 将合并后的 authorized_keys 分发到所有节点:

    scp ~/.ssh/authorized_keys user@node2:~/.ssh/
    scp ~/.ssh/authorized_keys user@node3:~/.ssh/
    

方法二:使用 ssh-copy-id(需首次输入密码)
在每台机器上执行:

ssh-copy-id user@node1
ssh-copy-id user@node2
ssh-copy-id user@node3

④ 设置严格的权限

所有机器上执行:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
  • 权限错误会导致免密登录失败

⑤ 测试免密登录

从任意机器(如 node1)测试:

ssh user@node2  # 应直接登录,无需密码
ssh user@node3
ssh node3       # 测试主机名解析是否生效

3. 高级配置(可选)

① 禁用 SSH 密码登录(增强安全)

编辑 /etc/ssh/sshd_config

sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config
sudo systemctl restart sshd
  • 确保免密登录测试成功后再操作

② 使用脚本自动化

node1 上运行以下脚本:

#!/bin/bash
NODES=("node1" "node2" "node3")
USER="user"

# 生成密钥(如果尚未生成)
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ""

# 分发公钥
for node in "${NODES[@]}"; do
  ssh-copy-id $USER@$node
done

# 测试免密登录
for node in "${NODES[@]}"; do
  ssh $USER@$node "echo '成功登录 $node'"
done

4. 故障排查

  • 主机名解析失败

    cat /etc/hosts     # 检查配置
    ping node2         # 测试解析
    
  • SSH 连接超时

    systemctl status sshd  # 检查 SSH 服务状态
    ufw status             # 检查防火墙规则
    
  • 权限问题

    chmod 700 ~/.ssh && chmod 600 ~/.ssh/*
    

5. 关键命令总结

步骤 命令
配置主机名解析 sudo tee -a /etc/hosts <<EOF
生成 SSH 密钥 ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""
分发公钥 ssh-copy-id user@nodeX 或手动合并 authorized_keys
测试免密登录 ssh user@node2
禁用密码登录 sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config

6. 安全建议

  1. 限制可登录用户

    echo "AllowUsers user" | sudo tee -a /etc/ssh/sshd_config
    sudo systemctl restart sshd
    
  2. 使用非默认 SSH 端口

    sudo sed -i 's/#Port 22/Port 2222/g' /etc/ssh/sshd_config
    sudo systemctl restart sshd
    
  3. 定期轮换密钥:重新生成并分发密钥对。


通过以上步骤,三台机器即可通过 IP 和主机名 实现双向免密互信,适用于集群管理、自动化运维等场景。

posted @ 2025-05-27 23:44  不断精进,终生成长  阅读(159)  评论(0)    收藏  举报