linux主机批量配置ssh互信脚本(多IP密码不同)

在这里插入图片描述
前提安装expect软件包。
创建ip.list文件,包含三个字段IP,USER,PASSWD,如:
192.168.112.10 root rootpasswd
192.168.112.11 root rootpasswd
192.168.112.12 root rootpasswd

#!/bin/bash
 
#生成密钥文件authorized_keys
cat ip.list|while read line
do
ip=`echo $line|cut -d' ' -f1`
user=`echo $line|cut -d' ' -f2`
passwd=`echo $line|cut -d' ' -f3`
#判断对应IP的目录是否存在,不存在,则自动创建
if [ ! -d /tmp/ssh/$ip ];
then
  mkdir -p /tmp/ssh/$ip
fi
#在对应的IP的服务器本机生成公钥文件id_rsa.pub
expect -c "
	spawn ssh $user@$ip ssh-keygen -t rsa
	expect {
    	\"password:\" {send \"$passwd\r\";}
   		\"yes/no\" {send \"yes\r\";}
    	\"Enter file in which to save the key*\" {send \"\r\";}
    	\"Enter passphrase*\" {send \"\r\";}
    	\"Enter same passphrase again:\" {send \"\r\";}
    	\"Overwrite (y/n)\" {send \"\r\";}
    }
expect eof"
#将各服务器的id_rsa.pub文件拷贝到本地/tmp/ssh的对应IP地址目下
expect -c "
spawn scp $user@$ip:~/.ssh/id_rsa.pub /tmp/ssh/$ip
  expect {
    \"yes/no\" {send \"yes\r\";}
    \"password:\" {send \"$passwd\r\";}
  }
expect eof"
#生成密钥认证文件authorized_keys
cat /tmp/ssh/$ip/id_rsa.pub >> /tmp/ssh/authorized_keys
done
#将authorized_keys文件scp到各个机器~/.ssh/下
cat ip.list|while read line
do
ip=`echo $line|cut -d' ' -f1`
user=`echo $line|cut -d' ' -f2`
passwd=`echo $line|cut -d' ' -f3`
expect -c "
spawn scp /tmp/ssh/authorized_keys $user@$ip:~/.ssh/ 
  expect {
    \"yes/no\" {send \"yes\r\";}
    \"password:\" {send \"$passwd\r\";}
  }
expect eof"
done

#bypass password
cat ip.list|while read line
do
ip=`echo $line|cut -d' ' -f1`
user=`echo $line|cut -d' ' -f2`
passwd=`echo $line|cut -d' ' -f3`
expect -c "
spawn ssh $ip 
  expect {
    \"yes/no\" {send \"yes\r\";}
  }
expect eof"
done
#删除临时目录
rm -fr /tmp/ssh

版权声明:本文为CSDN博主「丶大荡」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zyingpei/article/details/88639826

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值