#新建host文件,里面放需要复制公钥IP地址
[root@cent8 data]# cat host.txt
10.0.0.121
10.0.0.133
10.0.0.222
#分发公钥脚本
[root@cent8 data]# cat key.sh
#!/bin/bash
#
set -x
passwd=("redhat") #密码不同 passwd=("abc123" "abc1234")
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}
done
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.*
#执行脚本
[root@cent8 data]# sh key.sh host.txt
ssh-copy-id复制公钥到多台服务器脚本
于 2021-04-27 17:34:10 首次发布
本文介绍了一个Shell脚本,用于读取包含IP地址的host.txt文件,然后通过SSHpass和pssh工具分发本地RSA公钥到这些服务器上,实现免密登录。脚本首先检查并安装了pssh和sshpass,接着按顺序尝试用预设的密码连接服务器,并将公钥复制到远程主机的authorized_keys文件中。
摘要由CSDN通过智能技术生成