CentOS利用expect批量推送ssh public key的脚本

方法1:

#!/bin/bash
#
#********************************************************************
#Author:            Razor
#QQ:                254456122
#Date:              2021-10-29
#FileName           sshkey.sh
#URL:               https://blog.csdn.net/mandarin_meng?spm=1019.2139.3001.5343
#Description        The test script
#Copyright (C):     2021 All rights reserved
#********************************************************************
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
COLOR="echo -e \E[1;32m"
END="\E[0m"
PASSWORD=123456
IPLIST="
192.168.8.8
192.168.8.21
"
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -P "" -f ~/.ssh/id_rsa &>/dev/null
rpm -q expect &> /dev/null || yum -y -q install expect &>/dev/null
for ip in $IPLIST ;do
{
expect <<EOF
set timeout 60
spawn ssh-copy-id $ip
expect {
        "yes/no" { send "yes\r";exp_continue }
        "password:" { send "$PASSWORD\r" }
}
expect eof
EOF
$COLOR"$ip is ready"$END
}&
done
wait
$COLOR"Push ssh key is finished!"$END

范例:基于key验证实现批量主机管理

[root@cent8 data]#cat host.txt
192.168.8.8
192.168.8.21

[root@cent8 data]#for i in `cat host.txt`;do ssh $i hostname -I ;done
192.168.8.8
192.168.8.21

方法2:

或者将远程需要推送的主机列表放到一个文件中,这样以后就不需要每次都修改脚本了

#!/bin/bash
#
#********************************************************************
#Author:            Razor
#QQ:                254456122
#Date:              2021-10-29
#FileName           sshkey1.sh
#URL:               https://blog.csdn.net/mandarin_meng?spm=1019.2139.3001.5343
#Description        The test script
#Copyright (C):     2021 All rights reserved
#********************************************************************
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
PASS=123456
rpm -q expect &> /dev/null || yum -y install expect &> /dev/null
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen  -t rsa -P "" -f /root/.ssh/id_rsa &> /dev/null && echo "ssh key is created"
while read IP ;do
expect <<EOF &> /dev/null
set timeout 20
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$IP
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$PASS\r" }
}
expect eof
EOF
echo $IP is ready
done < hosts.txt
[root@cent8 data]#cat hosts.txt
192.168.8.8
192.168.8.21
[root@cent8 data]#
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mandarin_meng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值