前提安装expect软件包。
创建ip.list文件,包含三个字段IP,USER,PASSWD,如:
192.168.112.10 root rootpasswd
192.168.112.11 root rootpasswd
192.168.112.12 root rootpasswd
#!/bin/bash
#生成密钥文件authorized_keys
cat ip.list|while read line
do
ip=`echo $line|cut -d' ' -f1`
user=`echo $line|cut -d' ' -f2`
passwd=`echo $line|cut -d' ' -f3`
#判断对应IP的目录是否存在,不存在,则自动创建
if [ ! -d /tmp/ssh/$ip ];
then
mkdir -p /tmp/ssh/$ip
fi
#在对应的IP的服务器本机生成公钥文件id_rsa.pub
expect -c "
spawn ssh $user@$ip ssh-keygen -t rsa
expect {
\"password:\" {send \"$passwd\r\";}
\"yes/no\" {send \"yes\r\";}
\"Enter file in which to save the key*\" {send \"\r\";}
\"Enter passphrase*\" {send \"\r\";}
\"Enter same passphrase again:\" {send \"\r\";}
\"Overwrite (y/n)\" {send \"\r\";}
}
expect eof"
#将各服务器的id_rsa.pub文件拷贝到本地/tmp/ssh的对应IP地址目下
expect -c "
spawn scp $user@$ip:~/.ssh/id_rsa.pub /tmp/ssh/$ip
expect {
\"yes/no\" {send \"yes\r\";}
\"password:\" {send \"$passwd\r\";}
}
expect eof"
#生成密钥认证文件authorized_keys
cat /tmp/ssh/$ip/id_rsa.pub >> /tmp/ssh/authorized_keys
done
#将authorized_keys文件scp到各个机器~/.ssh/下
cat ip.list|while read line
do
ip=`echo $line|cut -d' ' -f1`
user=`echo $line|cut -d' ' -f2`
passwd=`echo $line|cut -d' ' -f3`
expect -c "
spawn scp /tmp/ssh/authorized_keys $user@$ip:~/.ssh/
expect {
\"yes/no\" {send \"yes\r\";}
\"password:\" {send \"$passwd\r\";}
}
expect eof"
done
#bypass password
cat ip.list|while read line
do
ip=`echo $line|cut -d' ' -f1`
user=`echo $line|cut -d' ' -f2`
passwd=`echo $line|cut -d' ' -f3`
expect -c "
spawn ssh $ip
expect {
\"yes/no\" {send \"yes\r\";}
}
expect eof"
done
#删除临时目录
rm -fr /tmp/ssh
版权声明:本文为CSDN博主「丶大荡」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zyingpei/article/details/88639826