看懂该脚本需要具备linux和shell基础:初中级LInux运维工程师在线评测

下面是shell脚本的内容:

#!/usr/bin/env bash
 
>send.log    #清空日志文件
echo -e "\nfind expect...\n"
if [ ! -f "/usr/bin/expect" ]        #判断是否安装expect,没有则安装,有则跳过
then
	echo -e "expect installing...\n"
	echo "2399" | sudo -S apt install expect -y >/dev/null 2>&1
	echo -e "expect install done\n"
else
echo -e "expect installed\n"
echo -e "check RSA public-private & send...\n"
while read -r line;do        #读取data.conf文件中的IP地址
{
	/usr/bin/expect<<EOF >>send.log #记录到日志文件
	set timeout 5
    #远程ssh执行命令生成私钥公钥,expect判断存在则继续
	spawn ssh user@${line} "ssh-keygen"    
	expect {
		"yes/no" { send "yes\r"; exp_continue }
		"password" { send "2399\r"; exp_continue }
		"password" { send "2399\r"; exp_continue }
		"Password" { send "2399\r";exp_continue }
		"id_rsa" { send "\r";exp_continue }
		"y/n" { send "n\r";exp_continue }
		"passphrase" { send "\r";exp_continue }
		"again" { send "\r" }
	}
    #拷贝自己的公钥到目标用户@地址
	spawn ssh-copy-id -i /home/user/windows/puttykegen/crt.pub user@${line}
	expect {
		"yes/no" { send "yes\r"; exp_continue }
		"password" { send "2399\r"; exp_continue }
		"password" { send "2399\r"; exp_continue }
		"Password" { send "2399\r" }
	}
    #对端拷贝公钥到本地
	spawn ssh -t user@${line} "sudo ssh-copy-id -i /home/user/.ssh/id_rsa.pub user@10.4.20.61"
	expect {
		"for" { send "2399\r"; exp_continue }
		"yes/no" { send "yes\r"; exp_continue }
		"password" { send "2399\r"; exp_continue }
		"password" { send "2399\r"; exp_continue }
		"Password" { send "2399\r" }
	}
EOF
} 
 
done < data.conf 
wait
echo -e "send id_rsa.pub done...\n"
echo "use time: ${SECONDS}s"
 
fi

运维工程师QQ在线交流群:580175957