ansible -01-2 批量分发公钥

0x00 前言

0x01 配置实例

使用交互shell推送公钥证书:

#!/bin/bash
yum install -y expect
#安装 expect

# set_ssh_keys.sh
password="123123"     ## 主机的密码,每个主机的密码要求一样
auto_ssh_copy_id() {
    expect -c "set timeout -1;
    spawn ssh-copy-id -i $2;
    expect {
  *(yes/no)* {send -- yes\r;exp_continue;}
        *assword:* {send -- $1\r;exp_continue;}
        eof        {exit 0;}
    }";
}
for i in $(</root/hosts)  ##主机ip文件,一行一个
do
     auto_ssh_copy_id $password $i
done

定义xml配置:

--
- hosts: "localhost"
  gather_facts: False
  tasks:
  - name: create user on ansible server as remote_user
    user: name="{{ user }}"
          generate_ssh_key=yes 
          ssh_key_type=rsa 
          ssh_key_bits=2048 
          ssh_key_file=.ssh/id_rsa 
          state=present
    tags: authorized-key
  
- hosts: "{{ hosts }}"
  tasks:
  - name: create user on remote host
    user: name="{{ user }}" state=present
    tags: authorized-key
  
  - set_fact: lookup_file_path="/root/.ssh/id_rsa.pub"
    when: user == "root"
    tags: authorized-key
  
  - set_fact: lookup_file_path="{{ '/home/'+user+'/.ssh/id_rsa.pub' }}"
    when: user != "root"
    tags: authorized-key
  
  - name: copy id_rsa.pub to remote host for authorized trust
    authorized_key: user="{{ user }}" key="{{ lookup('file',lookup_file_path) }}"
    tags: authorized-key

 执行配置:

ansible-playbook  authorized-key.yml -e "hosts=all user=ops" -k

0x02 效果

转载于:https://my.oschina.net/attacker/blog/679618

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值