简体   繁体   中英

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?

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

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"
done

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"
done

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")"
    else
        COUNT=0
    fi

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM