验证authorized_file中的所有公钥

验证authorized_file中的所有公钥

在我的 authorized_file 中,我有多个公钥对应一个私钥。现在我想在 ansible 中添加一个任务,该任务将验证所有公钥是否都是有效密钥并且适合连接。我的目标是从 authorized_file 中删除坏的/有故障的密钥。

答案1

您可以为此编写一个 Ansible 剧本,它将验证 authorized_file 中的所有公钥并删除无效的公钥,例如:

---
- name: Validate SSH public keys in authorized_file
  hosts: all
  gather_facts: no
  tasks:
    - name: Fetch the authorized_keys file
      slurp:
        src: ~/.ssh/authorized_keys
      register: authorized_keys_slurp

    - name: Extract the authorized_keys content
      set_fact:
        authorized_keys_content: "{{ authorized_keys_slurp['content'] | b64decode | regex_replace('\r\n', '\n') }}"

    - name: Validate each key and filter out invalid ones
      shell: echo "{{ item }}" | ssh-keygen -l -f /dev/stdin
      register: key_validation
      loop: "{{ authorized_keys_content.splitlines() }}"
      ignore_errors: true

    - name: Collect valid keys
      set_fact:
        valid_keys: "{{ valid_keys | default([]) + [item.item] }}"
      loop: "{{ key_validation.results }}"
      when: item.rc == 0

    - name: Update authorized_keys with valid keys only
      copy:
        content: "{{ valid_keys | join('\n') }}"
        dest: ~/.ssh/authorized_keys
        mode: 0600

为了使这项工作得以完成,请将其保存为.yml文件,然后您可以用您的库存文件 ansibleansible-playbook替换它来执行它-inventory.iniplaybook -i inventory.ini validate_authorized_keys.yml

相关内容