auto_keygen (){
/usr/bin/expect<<EOF
set timeout 30
spawn ssh-keygen
expect {
".ssh/id_rsa)" { send "
"; exp_continue }
"Overwrite (y/n)?" { send "y
"; exp_continue }
"no passphrase):" { send "
"; exp_continue }
"again:" { send "
"; exp_continue }
}
EOF
}
# 写个自动免密登录的函数
send_key () {
pwd=upsa
/usr/bin/expect <<EOF
set timeout 30
# 发送公钥给对方服务器
spawn ssh-copy-id root@$1
expect {
"yes/no" { send "yes
"; exp_continue }
"password:" { send "${pwd}
"; exp_continue }
}
expect eof
EOF
}
# 定义一个变量,其值是当前用户的公钥文件
pub_key_file=$HOME/.ssh/id_rsa.pub
# 假如公钥文件不存在,说明需要创建密钥对
if [ ! -f ${pub_key_file} ];then
auto_keygen
fi
# 循环一个存放 ip 地址的文件,并且把每个 IP地址传递给 函数
for ip in $(cat ./ips.txt)
do
send_key $ip
done