利用ssh-copy-id复制公钥到多台服务器

在做系统运维的时候,可能以免密码通过ssh方式登录到远程主机,这时就首先需要将本机的公钥复制到远程主机,用ssh-copy-id命令可以轻松做到。

如果没有生成密钥对,要先生成密钥,再将公钥复制到远程主机,username是远程主机的用户名,host是远程主机的ip地址或域名

#生成密钥
ssh-keygen -t rsa

#复制公钥到远程主机
ssh-copy-id username@host

对于单台远程主机,直接使用命令就可以了,但如果有很多台主机,需要一台台操作,就费时费力了。那么有什么好办法,能够一次性将公钥复制到所有主机呢?要解决这个问题,要自动处理在执行ssh-copy-id命令时两处需要手工介入的过程。

一是在看到类似如下提示时,要输入”yse“进行确认。

[@bjyf_50_20 ansible]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.160.64.106
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '10.160.64.106 (10.160.64.106)' can't be established.
RSA key fingerprint is SHA256:53H5SdUDggEJQH1HS9PX02tSXXiJXgBi1TX35dCVj0Y.
RSA key fingerprint is MD5:9b:be:a1:01:95:3f:30:68:7a:8b:bf:11:c8:ee:e6:f6.
Are you sure you want to continue connecting (yes/no)?

二是需要输入远程主机的密码

Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 2 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@10.160.64.106's password:

解决第一个问题,可以修改配置文件或运行ssh-copy-id命令加ssh的相关参数。

# -o StrictHostKeyChecking=no,连接新主机时,不进行公钥确认
 ssh-copy-id -o StrictHostKeyChecking=no root@10.160.64.106

或者在当前用户目录的.ssh/config文件,添加如下配置项,如果.ssh目录没有config文件,可自行创建。

StrictHostKeyChecking=no

接着来解决第二个问题,安装sshpass命令,在ubuntu中可以用apt命令直接安装,在Centos下可以使用yum命令直接安装

# ubuntu
apt -y install sshpass

# centos
yum -y install sshpass

通过安装好的sshpass命令,运行下面命令就能无需手工介入将ssh公钥复制到远程主机。

sshpass -p 'YOUR_PASSWORD' ssh-copy-id -o StrictHostKeyChecking=no root@10.160.64.106

如果使用修改配置文件的方式,可用下面的命令。

sshpass -p 'YOUR_PASSWORD' ssh-copy-id root@10.160.64.106

在解决了上面的两个问题之后,接下来的事情就简单了, 可以将远程主机的域名或IP地址记录在一个文件中,比如记录在remote-hosts文件中,运行下面的脚本就能批量的将公钥复制到远程主机中。

for host in $(cat remote-hosts)
do
   sshpass -p 'YOUR_PASSWORD' ssh-copy-id -o StrictHostKeyChecking=no root@${host}
done

注:上面的脚本是远程主机的密码都是相同,在命令行将密码硬编码写死,如果每台主机的密码不一样,可以将密码记录在remote-hosts文件中,通过cut命令分割,可以分别获得主机的IP地址或域名和对应的密码,当然如果ssh的端口号不是默认的22,也可以一并记录。如下列格式:

10.10.10.10:2222:YOURPASSWORD

可将上面的脚本稍做修改:

因为ssh-copy-id使用非默认端口时,需要加双引号,没有找到地的办法,取了个巧,先将整个命令放至一个临时文件。再执行该临时文件,执行之后,再删除。

for host in $(cat remote-hosts)
do
   ip=$(echo ${host} | cut -f1 -d ":")
   port=$(echo ${host} | cut -f2 -d ":")
   password=$(echo ${host} | cut -f3 -d ":")
  arg=$(echo -p ${port} -o StrictHostKeyChecking=no root@${ip})
  echo sshpass -p ${password} ssh-copy-id '"'${arg}'"' >> tmp.sh
done
sh tmm.sh
rm -f tmp.sh

生产应用

#新建hosts文件
[@bjyf_50_20 ansible]# cat host_test
10.160.9.162
10.160.24.163
[@bjyf_50_20 ansible]#
 
#分发公钥脚本
[@bjyf_50_20 ansible]# cat key.sh
#!/bin/bash
#
set -x

passwd=("abc123" "song_123")

PWD_IDX=$((${#passwd[@]}-1))

usage(){
    echo -e "\t\033[31m You entered an incorrent parameter \033[0m"
    echo -e "\t\033[31m Such as: $(basename $0) iplist\033[0m"
    exit 1
}

ins_pssh_sshpass(){
    os_version=$(awk -F"[ =\"]" '/^NAME/{print $3}' /etc/os-release)
    if [ "$os_version" = "Ubuntu" ];then
        dpkg -l | grep -q pssh && echo "pssh is already installed" || apt -y install pssh && ln -s /usr/bin/parallel-ssh  /usr/bin/pssh
        dpkg -l | grep -q sshpass && echo "sshpass is already installed" || apt -y install sshpass
    elif [ "$os_version" = "CentOS" ];then
        rpm -qa |grep -q pssh && echo "pssh is already installed" || yum -y install pssh
        rpm -qa |grep -q sshpass && echo "sshpass is already installed" || yum -y install sshpass
    fi
}

exec_ip(){
    sort -g ${INPUT_IP_FILE} > not_check_ip
    for i in $(seq 0 1)
    do
        if [ ! -s not_check_ip ];then
          continue
        fi
        sshpass -p"${passwd[$i]}" pssh -iAh not_check_ip -l root -p 100 -O StrictHostKeyChecking=no -t 5 "whoami" \
        |grep SUCCESS \
        |awk '{print $NF}'|sort -g>ip.$i
        grep -vFf ip.$i not_check_ip |sort -g > not_check_ip.tmp
        mv not_check_ip.tmp not_check_ip
    done
}

exec_key(){
    sshkey=$(ls ~/.ssh/id_rsa.pub)
    [ -f "${sshkey}" ] && echo "key exists" || ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
    for i in $(seq 0 ${PWD_IDX})
    do
        if [ ! -e ip.$i ];then
            break
        fi
        if [ -e ip.$i -a $(wc -l ip.$i|awk '{print $1}') -gt 0 ];then
            echo "---------------------------------------------------"

            for ip in $(cat ip.$i)
            do
                {
                    arg="ssh-copy-id -i ${sshkey} -o StrictHostKeyChecking=no root@$ip"
                    echo "sshpass -p${passwd[$i]} ${arg}"
                    sshpass -p${passwd[$i]} ${arg} >/dev/null 2>&1 
                }&
            done
            wait
        fi
    done
}
if [ $# -lt 1 ];then
    usage
fi
INPUT_IP_FILE=$1
ins_pssh_sshpass
if [ $? -ne 0 ];then
    exit
fi
exec_ip
exec_key
rm -f ip.*
[@bjyf_50_20 ansible]#
 
#执行脚本
[@bjyf_50_20 ansible]#bash -x key.sh host_test

注意:有坑!!!

坑1:由于 Centos 和 Ubuntu 默认运行的 shell 不同,所以使用 sh key.sh host_test在 Ubuntu 上执行脚本会报错

root@ubuntu20:~# sh key.sh hosts.txt
key.sh: 5: Syntax error: "(" unexpected
root@ubuntu20:~#

查看

[root@centos8 ~]#ll /bin/sh
lrwxrwxrwx 1 root root 4 Jul 22  2020 /bin/sh -> bash*
[root@centos8 ~]#

root@ubuntu20:~# ll /bin/sh
lrwxrwxrwx 1 root root 4  3月 13 15:47 /bin/sh -> dash*
root@ubuntu20:~#

所以为了避免不必要的麻烦,我们可以这样执行

bash -x key.sh host_test

坑2:Ubuntu 安装 pssh 后,并不能使用 pssh 命令,而是使用的是 parallel-ssh 命令,所以需要做一个软连接

ln -s /usr/bin/parallel-ssh  /usr/bin/pssh

root@ubuntu20:~# ll /usr/bin/pssh
lrwxrwxrwx 1 root root 21  4月 27 10:36 /usr/bin/pssh -> /usr/bin/parallel-ssh*
root@ubuntu20:~#

坑3:出于安全考虑,Ubuntu默认不允许root用户远程登录,需要手动设置

# 非交互模式设置root密码
# 错误
root@ubuntu20:~# echo "root:song123"|chpasswd
BAD PASSWORD: The password is shorter than 8 characters
root@ubuntu20:~# echo "root:song1234"|chpasswd
BAD PASSWORD: The password fails the dictionary check - it is too simplistic/systematic

# 正确
root@ubuntu20:~# echo "root:song_123"|chpasswd
root@ubuntu20:~#

# 修改 ssh 配置文件(/etc/ssh/sshd_config)将 PermitRootLogin 设置为 yes
root@ubuntu20:~# grep ^PermitRootLogin /etc/ssh/sshd_config
PermitRootLogin yes
root@ubuntu20:~#