我的解决方案是将expect的执行代码放在一个函数中,之后通过bash的方式,将函数的执行过程放到垃圾桶去(/dev/null),具体代码如下:
#!/usr/bin/bash
rpm -q expect &>/dev/null
if [ $? -ne 0 ];then
echo "installing expect ..."
yum install -y expect &>/dev/null
echo "installed ..."
fi
if [ ! -f ~/.ssh/id_rsa ];then
echo "create id_rsa and id_rsa.pub file..."
ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa &>/dev/null
echo "created successful!"
fi
>ip.txt
password=1
thread=10
fifodir=/tmp/fifo.txt
mkfifo $fifodir
exec 8<>$fifodir
rm -f $fifodir
for i in `seq $thread`
do
echo >&8
done
function f_pk(){
(
expect -c " # -c选项表示在命令行中执行
spawn ssh-copy-id $1 # 开启一个会话,推送公钥文件
set timeout 10 # 定义超时时间
expect {
# 如果匹配找到"yes/no"字符串,选yes
\"yes/no\" { send \"yes\n\";exp_continue }
# 如果匹配到"password"字符串,填之前定义好的密码
\"password:\" { send \"$password\r\"};
}
# 结束expect
expect eof
"
)
}
echo "pushing ..."
for i in {1..10}
do
read -u 8
{
ip=10.0.0.$i
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip" >> ip.txt
f_pk $ip &>/dev/null
fi
echo >&8
}&
done
wait
exec 8<&-
echo "push successful.."