#!/bin/bash
#获取内网eth1 ip地址
IP=`ip address show eth1|awk -F"[ /]+" '/inet /{print $3}'`
#截取网络位
NET=${IP%.*}
#主机密码
PASSWD=your_password
#主机位起止
BEGIN=1
END=253
#秘钥存放位置
KEY_PATH=/root/.ssh/
KEY_FILE=id_rsa
#安装sshpass
. /etc/os-release
if [ $ID=rocky -o $ID=centos ];then
	 rpm -q sshpass &>/dev/null||yum install -y sshpass &>/dev/null || { echo "请检查是否有epel源";sleep 3;exit 1 ;}
 else
	dpkg -i sshpass &>/dev/null||apt install sshpass -y &>/dev/null || { echo "请检查是否有epel源";sleep 3;exit 1; }
fi

#判断是否已经生成ssh秘钥
if [ ! -f ${KEY_PATH}${KEY_FILE}  ] ;then
	ssh-keygen -P "" -q -f ${KEY_PATH}${KEY_FILE}
fi
#判读文件是否存在如存在则清空
if [ -f ./iplist.txt ]; then
	>./iplist.txt
fi
#获取网段主机ip列表并写入文件
for (( i=${BEGIN}; i<=${END};i++ )) do
	ping -w1 -c1 ${NET}.$i >>/dev/null && echo ${NET}.$i >>./iplist.txt &
done
wait
#写入公钥并且复制known_hosts文件
while read IP_ADDR 
do
	sshpass -p $PASSWD ssh-copy-id -i /root/.ssh/id_rsa.pub -o StrictHostKeyChecking=no root@${IP_ADDR} &>/dev/null &&sshpass -p$PASSWD scp -r -o StrictHostKeyChecking=no  ${KEY_PATH}known_hosts root@${IP_ADDR}:${KEY_PATH} $>/dev/null
done<./iplist.txt
#删除ip列表文件
rm -f ./iplist.txt
