利用shell脚本实现-远程批量分发ssh公钥

需求描述:

在日常运维中,假设有一批机器刚刚上线,你需要远程将本机的公钥分发到没一台服务器, 使用expect实现非交互创建会话,使用while循环读取ip.txt表里面的没一行ip地址

#!/usr/bin/bash
# ssh-copy public 
# v1.0 by ytchen5 2020年11月21日
>good_ip.txt
expect_state=$(basename $(which expect))
password=merlin
username=root
if [ $# -eq 0 ];then
        echo "usage:`basename $0` file"
        exit 1
fi

if [ ! -f $1 ];then
        echo "usage:`basename $0` file"
        exit 2
fi

if [ ! ${expect_state} = "expect" ];then
	echo "expect no install"
	exit 3
fi

if [ ! -f /root/.ssh/id_rsa ];then
	echo "ssh-key no such file"
	ssh-keygen -P "" -f /root/.ssh/id_rsa
fi

while read ip
do
	{
	ping -c1 -W1 $ip &>/dev/null
	if [ $? -eq 0 ];then
		echo $ip >>good_ip.txt
	fi
	for i in `cat good_ip.txt`
	do
	expect <<-EOF
	spawn ssh-copy-id $username@$i
	expect {
	"yes/no" {send "yes\r"}
	"password" {send "$password\r"}
	}
	expect eof
	EOF
	done
	}&
done<$1
	echo "finishi.."

验证运行 前 每次ssh都需要输入yes和密码分发成功的话所有主机可以正常登录(不用输入密码)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值