生成 ssh 密钥并将 ssh 密钥复制到其他机器

Posted

技术标签:

【中文标题】生成 ssh 密钥并将 ssh 密钥复制到其他机器【英文标题】:ssh key generation and copy ssh key to other machines 【发布时间】:2021-08-26 08:38:17 【问题描述】:

我正在运行以下脚本来生成 ssh 密钥并将其复制到集群中的其他机器以实现无密码 ssh。

#!/bin/bash    
#create host and password file
echo enter host-name,password in "host pass" format:
read hopa
echo "$hopa"> /root/host1.txt
sed -i 's/,/\n/g' /root/host1.txt
# SSH Key
#echo -en "y" | ssh-keygen -f id_rsa -t rsa -N ''
# Passwordless ssh
echo -en "y" | ssh-keygen -f id_rsa -t rsa -N ''
    declare -A hp
    while IFS=' ' read -r host pass
do
        hp["$host"]="$pass"
    done < /root/host1.txt
   for host in "$!hp[@]"
    do
        pass="$hp["$host"]"
        sshpass -p "$pass[i]" ssh-copy-id -i id_rsa -o "StrictHostKeyChecking no" -f root@"$host[i]" -p 22
    done

当提示输入主机名及其密码时: 我的意见:

cephadmin 1234,ceph2 1234,ceph3 1234,cephclient 1234

输出:

The key fingerprint is:
    SHA256://CzhoYLtmVVRWoJTKfTkJV9BQbeKypzGoXBLV62KKw root@cephadmin
    The key's randomart image is:
    +---[RSA 3072]----+
    |         o+o+==.o|
    |       . .oB.*. .|
    |        + * B .. |
    |     . . B =   . |
    |      o S + . .  |
    |     . . + . .   |
    |    E o *.=.     |
    |     . =.*o+o    |
    |      . oo .+o   |
    +----[SHA256]-----+
    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
    
    Number of key(s) added: 1
    
    Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking no' -p '22' 'root@cephadmin'"
    and check to make sure that only the key(s) you wanted were added.
    
    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
    
    Number of key(s) added: 1
    
    Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking no' -p '22' 'root@ceph2'"
    and check to make sure that only the key(s) you wanted were added.
    
    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
    
    Number of key(s) added: 1
    
    Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking no' -p '22' 'root@ceph3'"
    and check to make sure that only the key(s) you wanted were added.
    
    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
    
    Number of key(s) added: 1
    
    Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking no' -p '22' 'root@cephclient'"
    and check to make sure that only the key(s) you wanted were added.
    

当我尝试使用 ssh cephclient 登录 cephclient 机器时,系统会提示我输入密码

[root@localhost ~]# ssh cephclient
    root@cephclient's password:

如何确保我的脚本正常运行并获得所需的输出,即无需密码即可登录其他机器?

【问题讨论】:

【参考方案1】:

第一次它会询问密码。从第二次开始,它不会询问密码。

【讨论】:

以上是关于生成 ssh 密钥并将 ssh 密钥复制到其他机器的主要内容,如果未能解决你的问题,请参考以下文章

如何生成SSH key

使用 ssh 密钥登录到 windows openssh 服务器

SSH免密登录

如何将已生成的 SSH 密钥添加到 git bash?

Mac下配置远程Linux 服务器SSH密钥认证自动登录

OPENWRT中SSH免密钥登陆(具体步骤)