ssh-copy-id复制公钥到多台服务器脚本

本文介绍了一个Shell脚本,用于读取包含IP地址的host.txt文件,然后通过SSHpass和pssh工具分发本地RSA公钥到这些服务器上,实现免密登录。脚本首先检查并安装了pssh和sshpass,接着按顺序尝试用预设的密码连接服务器,并将公钥复制到远程主机的authorized_keys文件中。
摘要由CSDN通过智能技术生成
#新建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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

y_zilong

一分钱的肯定

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值