1、ip.txt
vi /root/shell/ip.txt
#IP 用户名 密码;空格隔开
changxin-132 root Api03132
changxin-133 root Api03133
changxin-134 root Api03134
changxin-135 root Api03135
2、ssh-auto.sh
版本-1
#!/bin/bash
while read line
do
#获取IP
ip=`echo $line | cut -d " " -f1`
#获取用户名
user_name=`echo $line | cut -d " " -f2`
#获取密码
pass_word=`echo $line | cut -d " " -f3`
# echo $ip $user_name $pass_word
#生成ssh key
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
#检测是否安装 expect
if ! expect -v &>/dev/null;then
echo "install expect $ip"
yum -y install expect
fi
#expect 交互过程
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(未验证)
#!/bin/bash
# 生成ssh key
if [[ ! -f "/root/.ssh/id_rsa" ]];then
echo "gen ssh key"
ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
fi
# 检测是否安装了 expect
if ! expect -v &>/dev/null;then
echo "install expect"
yum install expect -y
fi
# 循环文件中的ip
for p in $(cat host.txt|grep -v '#');do
ip=$(echo "$p"|cut -f1 -d":") # 取出当前IP
password=$(echo "$p"|cut -f2 -d":") # 取出当前密码
# expect 交互过程
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
#-----------
# ip:password
#192.168.1.110:7758521
#192.168.1.111:7758521
#192.168.1.112:7758521
#-----------
3、执行
#执行权限
chmod +x /root/shell/ssh-auto.sh
#执行脚本
sh ssh-auto.sh
4、ssh验证
ssh changxin-133 hostname