Praveen sivadasan Praveen sivadasan - 1 year ago 43
Bash Question

How can i get all the users and their authorize_key in linux using shell script?

I am using the following script to get the key count. But its is not working, is any other method exists? or how should i fix the error?

for i in `cat /etc/passwd` ; do\
echo $i |\
awk -F: { print `grep -o "ssh-rsa" <<< (cat /home/"$1"/ .ssh/authorized_keys ) | wc -l` }

Answer Source

If you just want to display the number of keys, you can do this:

for homedir in $(awk -F':' '{print $6}' /etc/passwd); do
    [[ -f "${homedir}/.ssh/authorized_keys" ]] && cat "${homedir}/.ssh/authorized_keys"

To display the counts for each file:

for homedir in $(awk -F':' '{print $6}' /etc/passwd); do
    [[ -f "${homedir}/.ssh/authorized_keys" ]] && wc -l "${homedir}/.ssh/authorized_keys"

To display the counts by username:

while IFS='' read -r line || [[ -n "$line" ]]; do
    USERNAME="$(echo "$line" | awk -F: '{print $1}')"
    HOMEDIR="$(echo "$line" | awk -F: '{print $6}')"

    if [[ -f "${HOMEDIR}/.ssh/authorized_keys" ]]; then
        COUNT="$(grep -c 'ssh-' "${HOMEDIR}/.ssh/authorized_keys")"

    echo "${USERNAME} has ${COUNT} keys."
done < "/etc/passwd"