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

时间:2016-07-11 07:02:52

标签: linux bash shell centos

我使用以下脚本来获取密钥计数。但是它不起作用,是否存在任何其他方法?或者我该如何修复错误?

#!/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 个答案:

答案 0 :(得分:3)

如果您只想显示键数,可以执行以下操作:

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

显示每个文件的计数:

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

按用户名显示计数:

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"