AWK 和 Bash:检查用户的主页是否由用户拥有

AWK 和 Bash:检查用户的主页是否由用户拥有

我正在尝试使用单行命令循环访问 /etc/passwd ,以便找到那些拥有不属于该用户的主目录的用户。

以下内容有语法错误,但希望能说明这个概念。

awk -F: 'BEGIN{nores=1;} {if(system( "[ -d " $6 " ]") == 0 && $7 != "/sbin/nologin" && $(system( "ls -ld $6 | awk \'{print $3}\')" ) != $1 ) {print "The directory " $6 " exists for user " $1 " but is not owned by that user"; nores=0 }} END{if (nores) print "No results";}' /etc/passwd

这与针对某些内部测试的 CIS RHEL6 基准项目 9.1.13 的编写检查相关。

我可能会使用的解决方案,这有助于解决我做错的事情:

awk -F: 'BEGIN { FS = ":"; nores = 1; } { if ((system("[ -d " $6 " ]") == 0) && ($7 != "/sbin/nologin")) { "stat -c \"%U\" " $6 | getline s; if (s != $1) { print "The directory " $6 " exists for user " $1 " but is not owned by that user"; nores = 0 } } } END { if (nores) print "No results"; }' /etc/passwd

另一种解决方案,但通过将其放在一行上来使其满足要求::

flag=0; testuser=$(stat "/home/testuser" -c %U); while IFS=':' read -r myuser a b c d mydir e; do if [ -d "$mydir" -a "$e" != "/sbin/nologin" ]; then if [ "$myuser" != "$testuser" -a "$myuser" != $(stat "$mydir" -c %U) ]; then echo "The directory $mydir exists for user $myuser but is not owned by that user"; flag=1; fi fi done </etc/passwd; if [ $flag -eq 0 ]; then echo "No results"; fi

答案1

flag=0
testuser=$(stat "/home/testuser" -c %U)
while IFS=':' read -r myuser a b c d mydir e
do
    if [ -d "$mydir" -a "$e" != "/sbin/nologin" ]
    then
        if [ "$myuser" != "$testuser" -a \
             "$myuser" != $(stat "$mydir" -c %U) ] 
        then
            echo "The directory $mydir exists for user $myuser" \
                 "but is not owned by that user"
            flag=1
        fi
    fi
done </etc/passwd
if [ $flag -eq 0 ]
then
    echo "No results"
fi

答案2

或者你的awk可能是:

awk -F: 'BEGIN { FS = ":"; nores = 1; } { if ((system("[ -d " $6 " ]") == 0) && ($7 != "/sbin/nologin")) { "stat -c \"%U\" " $6 | getline s; if (s != $1) { print "The directory " $6 " exists for user " $1 " but is not owned by that user"; nores = 0 } } } END { if (nores) print "No results"; }' /etc/passwd

答案3

perl -F: -anE 'if( (stat $F[5])[4] != $F[2] )
                   { say "$F[0]($F[2]) not own $F[5]" }' /etc/passwd 

你几乎得到了你想要的。在 /etc/passwd 中:

  • F0 = 用户名
  • F5 = 主页
  • F2=uid
  • stat FileOrDir [4]是 FileOrDir 的 uid

添加更多条件来调整它。例子:

perl -F: -anE 'if( -d $F[5]  and               # F5 is a directory and
                   (stat $F[5])[4] != $F[2]    # owner(home) isNot uid
                 ) { say ...

相关内容