Skip to content

Instantly share code, notes, and snippets.

@stayallive
Created April 17, 2026 10:11
Show Gist options
  • Select an option

  • Save stayallive/21dcc7e2fa56c63731ddde387a44ea4b to your computer and use it in GitHub Desktop.

Select an option

Save stayallive/21dcc7e2fa56c63731ddde387a44ea4b to your computer and use it in GitHub Desktop.
Script to search for SSH keys on a server, list specific keys, and delete them
#!/bin/bash
# sshkeys.sh - list or remove SSH authorized_keys entries across all users
#
# Usage:
# sshkeys.sh List all keys
# sshkeys.sh PATTERN Show keys matching PATTERN (dry run)
# sshkeys.sh PATTERN --delete Remove matching keys (backs up as .bak)
set -uo pipefail
PATTERN="${1:-}"
MODE="${2:-}"
if [ "$MODE" = "--delete" ] && [ -z "$PATTERN" ]; then
echo "Refusing to delete without a pattern." >&2
exit 1
fi
found=0
while IFS= read -r home; do
[ -n "$home" ] || continue
for suffix in "" "2"; do
file="${home}/.ssh/authorized_keys${suffix}"
[ -s "$file" ] || continue
if [ -z "$PATTERN" ]; then
echo "### $file"
cat "$file"
echo
found=1
continue
fi
if grep -qF -- "$PATTERN" "$file"; then
echo "### $file"
grep -nF -- "$PATTERN" "$file"
found=1
if [ "$MODE" = "--delete" ]; then
cp -p "$file" "${file}.bak"
tmp=$(mktemp)
grep -vF -- "$PATTERN" "$file" > "$tmp" || true
cat "$tmp" > "$file" # overwrite in place, preserves perms/owner
rm -f "$tmp"
echo " -> removed matching lines (backup: ${file}.bak)"
fi
echo
fi
done
done < <(cut -f6 -d ':' /etc/passwd | sort -u)
if [ "$found" -eq 0 ]; then
[ -n "$PATTERN" ] && echo "No matches for: $PATTERN" >&2 \
|| echo "No authorized_keys files found." >&2
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment