批量分发ssh公钥证书

脚本代码

  • 主程序,init_host.sh 功能,读取 /root/hostlist 列表内的IP,密码,主机名,批量执行如下设置;
  • 将脚本,配置文件拷贝远端主机指定位置
  • 执行远端主机/root/remote_operate.sh脚本
  • 设置主机名,安装salt-minion
#!/bin/bash
PUB_KEY="/root/.ssh/authorized_keys"
SALT_CONF="/etc/apt/sources.list.d/saltstack.list"
HOST_LIST="/root/hostlist"

function run_remote_cmd()
{
local cmd=$1
expect -c "
spawn ${cmd}
expect {
                \"*yes/no*\" {send \"yes\r\"; exp_continue}
                \"*password*\" {send \"$password\r\"; exp_continue}
                \"*Password*\" {send \"$password\r\";}
        }
"   
}

for i in $(cat $HOST_LIST)
do
        ip=$(echo "$i"|cut -f1 -d":")
        password=$(echo "$i"|cut -f2 -d":")
        host_name=$(echo "$i"|cut -f3 -d":")

        run_remote_cmd "scp ${PUB_KEY}  /root/remote_operate.sh  root@${ip}:/tmp/"
        run_remote_cmd "scp ${SALT_CONF} root@${ip}:/etc/apt/sources.list.d/saltstack.list"
        run_remote_cmd "ssh root@${ip} echo ${host_name} > /etc/hostname"
        run_remote_cmd "ssh root@${ip} /tmp/remote_operate.sh"
        run_remote_cmd "ssh root@${ip} apt-get update && apt-get install salt-minion --force-yes -y"
        
done
  • /root/remote_operate.sh 分发给远端机器的脚本,用于设置ssh_auth
#!/bin/bash
source ~/.bashrc

if [ ! -d /root/.ssh ];then
mkdir /root/.ssh
fi
if [ -f /root/.ssh/  ];then
    cat /tmp/authorized_keys >> /root/.ssh/authorized_keys
else
    cp /tmp/authorized_keys /root/.ssh/
fi
  • /root/hostlist
10.2.0.111:123Abcd:ubuntu-server-001
10.2.0.112:123Abcd:ubuntu-server-002

解析一下要点

1 run_remote_cmd() 函数调用了 expect -c "cmd ..." 相当于在shell脚本中插入一段 expect执行代码;
2 exp_continue, 可以不断循环匹配,详细见expect 的匹配循环

参考

1 http://www.linuxidc.com/Linux/2012-06/62663.htm 2 http://wangxu.me/blog/p/tag/exp_continue

转载于:https://my.oschina.net/u/877567/blog/189764

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值