需求描述:
在日常运维中,假设有一批机器刚刚上线,你需要远程将本机的公钥分发到没一台服务器, 使用expect实现非交互创建会话,使用while循环读取ip.txt表里面的没一行ip地址
#!/usr/bin/bash
# ssh-copy public
# v1.0 by ytchen5 2020年11月21日
>good_ip.txt
expect_state=$(basename $(which expect))
password=merlin
username=root
if [ $# -eq 0 ];then
echo "usage:`basename $0` file"
exit 1
fi
if [ ! -f $1 ];then
echo "usage:`basename $0` file"
exit 2
fi
if [ ! ${expect_state} = "expect" ];then
echo "expect no install"
exit 3
fi
if [ ! -f /root/.ssh/id_rsa ];then
echo "ssh-key no such file"
ssh-keygen -P "" -f /root/.ssh/id_rsa
fi
while read ip
do
{
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo $ip >>good_ip.txt
fi
for i in `cat good_ip.txt`
do
expect <<-EOF
spawn ssh-copy-id $username@$i
expect {
"yes/no" {send "yes\r"}
"password" {send "$password\r"}
}
expect eof
EOF
done
}&
done<$1
echo "finishi.."
验证