【问题标题】:How to ensure that root is the only UID 0 account?如何确保 root 是唯一的 UID 0 帐户?
【发布时间】:2022-01-26 13:26:04
【问题描述】:

我创建了两个用户 testtest2,其 UID 为 0 和 1001。当我运行这个脚本时,第一个条件是 $i != "root",所以输出是它同时打印 test 和 @987654325 @ 但不是root。但是我的第二个条件不起作用。

#!/bin/bash

result="$(awk-F: '($3 == 0) { print $1 }' /etc/passwd)"
uid=$(stat --format=\%u /etc/passwd)

for i in $result
do 
    if [ $i != "root" ] && [[ "$uid" -eq 0 ]]; then
    grep ^i /etc/passwd | cut -d: -f1,3
fi
done

【问题讨论】:

    标签: linux bash


    【解决方案1】:

    为什么不从一开始就使用 awk 呢?

    #!/bin/bash
    
    users=( $(awk -F: '$3 == 0 && $1 != "root" {print $1}' /etc/passwd) )
    
    if [[ ${#users[@]} != 0 ]]
    then
        echo "non-root users with uid = 0: ${users[*]}"
    fi
    

    或者通过使用 awk 返回非零退出代码并同时保存输出:

    #!/bin/bash
    
    if users=($(awk -F: '$3==0 && $1!="root"{print $1;rc=1}END{exit !rc}' /etc/passwd))
    then
        echo "non-root users with uid = 0: ${users[*]}"
    fi
    

    【讨论】:

    • 如果可能的话,我打算在满足条件后回显或显示“非root用户和uid = 0”。
    • 更新了答案以将 uid=0 的非 root 用户保存在 bash 数组中
    • 它没有显示任何输出
    • 对不起,我忘了否定第二个例子中的结果
    • 我删除了 rc 并且脚本可以工作
    猜你喜欢
    • 2015-05-17
    • 2017-06-06
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多