1、ip.txt
vi /root/shell/ip.txt
changxin-132 root Api03132
changxin-133 root Api03133
changxin-134 root Api03134
changxin-135 root Api03135
2、ssh-auto.sh 版本-1
while read line
do
ip=`echo $line | cut -d " " -f1`
user_name=`echo $line | cut -d " " -f2`
pass_word=`echo $line | cut -d " " -f3`
if [[ ! -f "/$user_name/.ssh/id_rsa" ]]; then
echo "gen ssh key $ip"
ssh-keygen -t rsa -b 2048 -N '' -f /$user_name/.ssh/id_rsa
fi
if ! expect -v &>/dev/null;then
echo "install expect $ip"
yum -y install expect
fi
expect << EOF
spawn ssh-copy-id -i /$user_name/.ssh/id_rsa.pub $user_name@$ip
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "$pass_word\n"}
}
expect eof
EOF
done < /root/shell/ip.txt
版本-2(未验证)
if [[ ! -f "/root/.ssh/id_rsa" ]];then
echo "gen ssh key"
ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
fi
if ! expect -v &>/dev/null;then
echo "install expect"
yum install expect -y
fi
for p in $(cat host.txt|grep -v '#');do
ip=$(echo "$p"|cut -f1 -d":")
password=$(echo "$p"|cut -f2 -d":")
expect -c "
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip
expect {
\"*yes/no*\" {send \"yes\r\"; exp_continue}
\"*password*\" {send \"$password\r\"; exp_continue}
\"*Password*\" {send \"$password\r\";}
}
"
host.txt
3、执行
chmod +x /root/shell/ssh-auto.sh
sh ssh-auto.sh
4、ssh验证
ssh changxin-133 hostname
|