You could do an Ansible playbook for that, it will validate all public keys in the authorized_file and remove the invalid ones, like for example:
---
- 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
To make this work save it as a .yml
file then you can execute it with ansible-playbook
replace inventory.ini
with your inventory file ansible-playbook -i inventory.ini validate_authorized_keys.yml