shell 脚本 实现批量互相传递ssh密钥

脚本实现了批量互相传递ssh密钥,使它们可以相互登录
alive.txt.tmp 是临时生成保存存活主机数的,可以再最后加上删除这个

逻辑:首先用ping来获取输入的存活主机,然后检查有没有sshpass和expect包,然后进行交互

#!/bin/bash
#
#********************************************************************
#Author:		liuhao
#QQ: 			1921160095
#Date: 			2019-11-06
#FileName:		ip.sh
#Description:		The test script
#Copyright (C): 	2019 All rights reserved
#********************************************************************
echo "实现了批量ssh 的相互传输,需要输入起始ip和结束ip。"
echo "仅支持最后一位的变动,如192.168.39.1~192.168.39.254"
echo "脚本需要依赖sshpass和expect两个软件包,如果未安装的话,配置好yum源即可"
read -p "请输入起始ip: " beginip
read -p "请输入结束ip: " endip
read -p "请输入本机ip: " localip
read -p "请输入用户: " user
read -p "请输入密码: " ymima
begarray=(${beginip//./ })
endarray=(${endip//./ })
rpm -q sshpass &> /dev/null || yum install sshpass -y &> /dev/null
rpm -q expect &> /dev/null || yum install expect -y &> /dev/null
#检测在线主机
[ -f alive.txt.tmp ] && rm -f alive.txt.tmp
if [ "${begarray[0]}" = "${endarray[0]}" -a "${begarray[1]}" = "${endarray[1]}" -a "${begarray[2]}" = "${endarray[2]}" ]; then
	while [ "${begarray[3]}" -le "${endarray[3]}" ];do
		#echo ${begarray[3]}
		{	
		if ping -c1 -w1 ${endarray[0]}.${endarray[1]}.${endarray[2]}.${begarray[3]} &> /dev/null ; then
			echo ${endarray[0]}.${endarray[1]}.${endarray[2]}.${begarray[3]} >> alive.txt.tmp
		fi
		}&	
		let begarray[3]++
	done
	wait
else
	echo 仅支持变动最后一位1~254
fi 
#让在线主机批量生成密钥对到一台主机
if [ -f alive.txt.tmp ];then
	while read aliveip;do
expect <<eof
set timeout 10
spawn ssh $user@$aliveip
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "$ymima\n";exp_continue}
"]#" {send "echo \n"}
}
expect "]#" {send "cat /etc/ssh/ssh_config | grep StrictHostKeyChecking\n"}
expect {
"ask" {send "sed -i '/Checking ask/c StrictHostKeyChecking no' /etc/ssh/ssh_config\n";exp_continue}
"]#" {send "ls /root/.ssh/\n"}
}
expect {
"id_rsa.pub" {send "rm -rf /root/.ssh/\n";exp_continue}
"]#" {send "ssh-keygen -P '' -f /root/.ssh/id_rsa &> /dev/null\nyum install sshpass -y\nsshpass -p $ymima ssh-copy-id -i  /root/.ssh/id_rsa.pub $localip\n"}
}
send "exit\n"
expect eof
eof
	done < alive.txt.tmp
fi
#分发公钥到其他主机
if [ -f alive.txt.tmp ];then
	while read aliveip;do
		sshpass -p $ymima scp /root/.ssh/authorized_keys "$aliveip":/root/.ssh/authorized_keys
	done < alive.txt.tmp
fi

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值