Bash 脚本:如何检查是否只有一个 root id?

Bash Scripting: How to check if there's is only one root id?

如何编辑我的脚本以检查是否只有一个根 ID?

预期输出

Audit criteria: There is only one root id

Vulnerability: Yes

Details: See below


root:!:0:0::/:/usr/bin/bash

jdoe:*:0:1:John Doe:/home/jdoe:/usr/bin/bash

剧本

#!/bin/bash

isVulnerable="No"
isVulnerable="Yes"    

cat /etc/passwd | cut -f3 -d":" | sort -n | /usr/bin/uniq -c | while read x ;            
do 
   [ -z "${x}" ] && break
   set - $x

if [ "" -gt 1 ]; then
    users=`/bin/gawk -F: '( == n) { print  }' n= /etc/passwd | /usr/bin/xargs`

echo "Audit Criteria: Duplicate UID (): ${users}"
echo "Vulnerability: ${isVulnerable}"
echo "Details: see below"
echo
grep "x:0:" /etc/passwd

else

echo "All user id are unique"
fi

done

你可以这样做:

ROOT_COUNT=$(cut -f3 -d":" </etc/passwd | grep -c ^0$)

然后,如果 ROOT_COUNT 包含大于 1 的内容,则您有多个 UID 为 0 的用户。

使用AWK收集重复字段的行非常方便:

get_dups() {
  awk -F':' ' == 0 { if (dup++) print } END { exit(dup > 1) }' /etc/passwd
}

如果 /etc/passwd 文件中有多个零用户 ID,函数以 non-zero 状态退出,并将具有重复根用户 ID 的行打印到标准输出。否则,退出状态为零。

用法:

dups="$(get_dups)"
if [ $? -eq 0 ]; then
  vulnerability='No'
  msg='There is only one root ID'
else
  vulnerability='Yes'
  msg='There are multiple root IDs'
fi
printf '%15s: %s\n' 'Audit criteria' "$msg"
printf '%15s: %s\n' 'Vulnerability' "$vulnerability"

[ -z "$dups" ] && dups='All user IDs are unique'
printf '\n%s\n' "$dups"