批量分发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

你可能感兴趣的:(批量分发ssh公钥证书)