[root@localhost ~]# cat ssh.sh
#!/bin/bash
echo -e -n "请输入\033[34mroot\033[0m用户密码 >>> "
read -p "" pwd
echo -e -n "请输入\033[34m本地ip\033[0m[如:192.168.2.10] >>> "
read -p "" local_ip
subnet=$(echo ${local_ip}|awk -F '.' '{print $1"."$2"."$3}')
yum_task(){
cmd_exist=$(which $1)
if [ -z ${cmd_exist} ]
then
yum install $1 -y
fi
}
# 自动向传入的IP地址拷贝密钥的函数
create_key(){
/usr/bin/expect <<EOF
# 设置捕获字符串后,期待回复的超时时间
set timeout 10
# 发送公钥给对方服务器
spawn ssh-keygen -t rsa
expect {
"Enter file" { send "\n"; exp_continue }
"Enter passphrase" { send "\n"; exp_continue }
"Enter same" { send "\n"}
}
expect eof
EOF
}
copy_key () {
#pwd='123'
# 开始 expect 解释器程序
/usr/bin/expect <<EOF
# 设置捕获字符串后,期待回复的超时时间
set timeout 30
# 发送公钥给对方服务器
spawn ssh-copy-id root@$1
expect {
"yes/no" { send "yes\n"; exp_continue }
"password:" { send "${pwd}\n"}
}
expect eof
EOF
}
ssh_port_check(){
echo '' | telnet $1 22 |grep -o -i Connected
}
[ -z $(rpm -qa |grep epel-release) ] && yum install -y epel-release
yum_task nmap
yum_task telnet
yum_task ansible
all_ip_list=$(nmap -sP ${subnet}.* | grep -o ${subnet}.*)
host_ip_list=''
for i in ${all_ip_list}
do
tag=$(ssh_port_check $i 2>/dev/null)
if [ ! -z ${tag} ]
then
host_ip_list="$i ${host_ip_list}"
fi
sleep 0.5
done
host_ip_list=${host_ip_list}
if [ ! -f /etc/ansible/hosts-bak ]
then
cp -p /etc/ansible/hosts /etc/ansible/hosts-bak
fi
if [ ! -f /root/.ssh/id_rsa.pub ]
then
create_key
fi
echo [group] > /etc/ansible/hosts
for host in ${host_ip_list}
do
echo ${host} >> /etc/ansible/hosts
done
# 循环把每个 Host 传递给自动拷贝函数
for host in $(ansible all --list-hosts |awk 'NR>1 {print $1}')
#for host in `cat iplist`
do
echo $host
copy_key $host
done
ssh-agent bash
# 开始 expect 解释器程序
/usr/bin/expect <<EOF
# 设置捕获字符串后,期待回复的超时时间
set timeout 30
# 发送公钥给对方服务器
spawn ssh-add
expect {
"id_rsa:" { send "${pwd}\n"}
}
expect eof
EOF