authorized-ssh-keys.sh 1.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#!/bin/bash
# Collect all SSH keys in use across salt minions' user accounts
#
# Copyright 2019-today
#
# Project WEBIS
# Author: Michael Völske

scriptPath=${0%/*}
. "$scriptPath"/../../libs/bashhelper.sh
. "$scriptPath"/../../libs/shflags

check_tools "ssh" "salt"

#
#    Define usage screen.
#
usage() {
    echo "usage: 
        $(basename "$0")

description:
        Collect all SSH keys occurring in .ssh/authorized_keys files across all reachable salt minions.
        Must be run from a salt master.
"
}

#
#    Define command line arguments and parse them.
#
FLAGS_HELP=$(usage)
export FLAGS_HELP
FLAGS "$@" || exit 1  # Parse command line arguments.
eval set -- "${FLAGS_ARGV}"


#
#    Main
#
main() {
    NUM_DEAD=0
Michael Völske's avatar
Michael Völske committed
42
    KEYCOUNT=0
43
    declare -A KPH
Michael Völske's avatar
Michael Völske committed
44
    LIST=$( mktemp )
45
    salt '*' cmd.run 'find /root /home -path "*/.ssh/authorized_keys" -maxdepth 4 -exec cat \{\} \;' --output=txt \
Michael Völske's avatar
Michael Völske committed
46 47
         | sort -t: -k2 -k1V \
         > $LIST
48

Michael Völske's avatar
Michael Völske committed
49 50 51
    while IFS=":" read -r -a LINE ; do
      H=${LINE[0]}
      K=${LINE[1]}
52

Michael Völske's avatar
Michael Völske committed
53 54
      if [[ $K =~ "did not return" ]]; then
          NUM_DEAD=$(( NUM_DEAD + 1))
Michael Völske's avatar
Michael Völske committed
55 56 57 58 59 60
          continue
      fi

      if [[ $K =~ ^[\ \t]*$ ]]; then K=""; fi

      if [[ $K != $LASTKEY && $K != "" ]]; then
Michael Völske's avatar
Michael Völske committed
61 62 63 64 65
          echo Key: $K
          echo Used on hosts:
          KEYCOUNT=$(( $KEYCOUNT + 1 ))
          LASTHOST=""
      fi
66

Michael Völske's avatar
Michael Völske committed
67 68 69 70 71
      if [[ $K != "" && $H != $LASTHOST ]]; then
          echo " - $H"
          LASTHOST=$H
          KPH[$H]=$(( ${KPH[$H]} + 1 ))
      fi
72

Michael Völske's avatar
Michael Völske committed
73 74 75
      LASTKEY=$K
    done < $LIST
    rm -f $LIST
Michael Völske's avatar
Michael Völske committed
76
    echo "TOTAL UNIQUE KEYS: $KEYCOUNT; $NUM_DEAD hosts offline; ${#KPH[@]} hosts online."
77 78 79 80 81 82
}
#
#    Start programm with parameters.
#
main "$@"