如何在Bash/sh中为数组分配用户帐户名和目录



我正试图在Red Hat Enterprise Linux(RHEL(系统上创建漏洞ID为V-72017的STIG测试的bash脚本。我的任务是确保所有用户权限的八进制值为0750或更低的

我有能力通过使用收集用户的权限八进制值

stat -c "%a" /home/$username

我正试图通过使用以下命令创建$username(或目录(数组(输出系统上每个用户的名称(:

eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)} | cut -d: -f1

我计划将这个输出映射到一个数组,可能是一个while循环。这是一个可能的解决方案吗?

以下语法错误:

(eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)} | cut -d: -f1) | while read -r line
do
myarray+=line
stat -c "%a" /home/$line
done

期望输出情况1:

Users:
rob
bob
Exit Fail: bob has permission octal value 0755.

期望输出情况2:

Users:
rob
bob
Exit Pass: All users have permission octal value of 0750 or less.

您已找到所有登录用户。Regexp可用于检查主目录的权限。

echo "Users: "                                                                   
(eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)} | cut -d: -f1) | while read -r line
do                                                                               
echo $line                                                                     
perm=$(stat -c "%a" /home/$line)                                               
[[ "$perm" =~ [0-7][0,1,4,5][0] ]] || echo "Exit fail: $line has permission octal value $perm"                                                                            
done

也许你想调整输出形式。

建议尽可能避免使用eval。更多如果您正在调查系统安全状态。请尝试取而代之的是:

#!/bin/bash
perm=0750       # system policy
uid_min=$(sed -n '/^UID_MIN/ s/[^0-9]*([0-9]+).*/1/p' "/etc/login.defs")
uid_max=$(sed -n '/^UID_MAX/ s/[^0-9]*([0-9]+).*/1/p' "/etc/login.defs")
# read /etc/passwd and process line by line
while IFS=: read -ra a; do
# now ${a[0]} holds username and ${a[2]} holds uid
if (( ${a[2]} >= uid_min && ${a[2]} <= uid_max )); then
# narrow down the users whose uid is within the range
users+=("${a[0]}")
# check the user's permission
userperm="0$(stat -c "%a" "/home/${a[0]}")"
if (( (~ perm) & userperm )); then
# the user's permission exceeds the limitation $perm
fail+=("$(printf "%s has permission octal value 0%o." "${a[0]}" "$userperm")")
fi
fi
done < "/etc/passwd"
echo "Users:"
for i in "${users[@]}"; do
echo "$i"
done
if (( ${#fail[@]} == 0 )); then
printf "Exit Pass: All users have permission octal value of 0%o or less.n" "$perm"
else
for i in "${fail[@]}"; do
printf "Exit Fail: %sn" "$i"
done
fi

希望这能有所帮助。