如何使用shell脚本获取linux中的所有用户及其authorize_key ?

时间:2021-06-25 23:52:28

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

1 个解决方案

#1


3  

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"

#1


3  

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"