使用ansible管理大量主机时,需要将密钥推送到被管理端,如果是虚拟机,可以在模板中将管理主机中的公钥直接写入到authorized_key,后期使用则不再关心密钥推送问题,非虚拟机或有定期更新密钥需求,则可以使用expect进行批量推送。

执行前需要安装expect包

yum install expect -y


推送脚本

#!/bin/bash
ssh_keygen(){
        ssh-keygen -t rsa -f /root/.ssh/id_rsa -q -P ''
}
send_key(){
/usr/bin/expect </dev/null
spawn  ssh-copy-id -i  $user@$ip
expect {
                "connecting (yes/no)?"  { send "yes\r"; exp_continue}
                "password:"             { send "$pass\r"}
}
        interact
expect eof
EOF
}
ssh_copy_id(){
cat ./hosts|while read line
do
        ip=`echo $line|awk '{print $1}'`
        user=`echo $line|awk '{print $2}'`
        pass=`echo $line|awk '{print $3}'`
        send_key $ip $user $pass
        if [ $? -eq 0 ]
        then
                echo "# `date +%F-%X` $ip copy id_rsa.pub success!"|tee -a ssh_copy_id_sucess.log
        else
                echo "# `date +%F-%X` $ip copy id_rsa.pub faild!"|tee -a ssh_copy_id_err.log
        fi
done
}
if [ ! -f ~/.ssh/id_rsa ];then
        ssh_keygen
        ssh_copy_id
else
        ssh_copy_id
fi

hosts文件格式如下:

IP USER PASSWORD