批量传输公钥shell脚本

批量传公钥

使用本脚本需要在创建/tmp/hosts文件,写入所有主机信息和密码格式为 hostname password
expect 实现非交互式应答 是自动应答命令用于交互式命令的自动执行
查看是否安装expect,判断返回值 需要安装 expect

#!/bin/bash
rpm -qa|grep expect &>/dev/null
[ "$(echo $?)" != "0" ] && yum -y install expect &>/dev/null && echo "expect install successfully" || echo "expect already exists!"


#统计主机清单行数
num=`cat /tmp/hosts | wc -l`

#利用for循环遍历所有行,截除每行的主机名和密码  
for i in `seq 1 $num`
do
    hostname=`sed -n "${i}p" /tmp/hosts|awk '{print $1}'`
    passwd=`sed -n "${i}p" /tmp/hosts|awk '{print $2}'`
    /usr/bin/expect <<EOF
    set timeout 300     
    spawn ssh-keygen
    expect "/root/.ssh/id_rsa"
    send "\n"
    expect {
            "Overwrite" { send "no\n" }
            "passphrase" { send "\n"; exp_continue }
            "again" { send "\n" }
    }

    spawn ssh-copy-id -i $hostname
    expect {
            "yes/no" { send "yes\n"; exp_continue }
            "password" { send "${passwd}\n" }
    }
    expect eof
EOF
done
#执行完成后删除主机清单
#rm -rf /tmp/hosts 
上一篇:05_SHELL编程之嵌套循环+随机数及综合案例


下一篇:centos7 通过shell切换root用户