SSH-免密登录

关键词:SSH 免密登录 passwordless 快速配置 免密操作

概览

SSH免密配置无论是在生产环境还是开发环境都是经常会用到的,本文不多讨论SSH协议诸多细节,聚焦在快速达到效果,SSH的免密配置通常有两种常见场景

  1. 管理机器免密登录其它机器
  2. 全部机器互相免密

A机器免密登陆B机器,需要把A机器的公钥(~/.ssh/id_rsa.pub),放到B机器的信任文件里(~/.ssh/authorized_keys)

下面分别看下,快速配置

管理机器免密登录其它机器

1 在管理机器上执行

ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa; cat ~/.ssh/id_rsa.pub

cat << 'EOF' >> ~/.ssh/authorized_keys
# 这里面的内容是在管理机器上 cat ~/.ssh/id_rsa.pub 得到的
EOF
chmod 0600 ~/.ssh/authorized_keys

2 在其它需要免密登录的机器执行

mkdir -p ~/.ssh && chmod 0700 ~/.ssh
touch ~/.ssh/authorized_keys && chmod 0600 ~/.ssh/authorized_keys

cat << 'EOF' >> ~/.ssh/authorized_keys
# 这里面的内容是在管理机器上 cat ~/.ssh/id_rsa.pub 得到的
EOF

正确权限配置参考

[root@192-168-31-106 ~]# ls -l ~/.ssh/
total 16
-rw------- 1 root root  792 Dec  1 17:35 authorized_keys
-rw------- 1 root root 1675 May 25  2020 id_rsa
-rw-r--r-- 1 root root  392 May 25  2020 id_rsa.pub
-rw-r--r-- 1 root root 1427 Dec  1 17:39 known_hosts
[root@192-168-31-106 ~]# ls -ld ~/.ssh/
drwx------ 2 root root 80 May 25  2020 /root/.ssh/

全部机器互相免密

  1. 多台机器全部执行一次 ssh-keygen -t rsa -P “” -f ~/.ssh/id_rsa ,该命令生成一个文本文件 ~/.ssh/id_rsa.pub
  2. 把多台机器 ~/.ssh/id_rsa.pub 这个文件里的内容集合起来,放到所有机器的 ~/.ssh/authorized_keys (这个文件之前可能不存在)
  3. 修改 ~/.ssh/authorized_keys 权限为 0600

    ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa; cat ~/.ssh/id_rsa.pub
    
    cat << 'EOF'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55Yhtlbr0fNfvbeQpgZVSBsuYvFEpzQWDAW2VcLHmZIoWWgIOWvp/0t5SlrlXO+XpDuZnkMeDvgenJH8OrrUlx2MGLXGbG+zyPAz// root@dpcdh003
    EOF
    chmod 0600 ~/.ssh/authorized_keys
    
    sed -i '/node/d' /etc/hosts
    echo '192.168.1.1 node1' >> /etc/hosts
    echo '192.168.1.2 node2' >> /etc/hosts
    echo '192.168.1.3 node3' >> /etc/hosts
    cat /etc/hosts
    

csdn 110442383